码迷,mamicode.com
首页 > 其他好文 > 详细

Pascal's Triangle

时间:2015-03-12 16:58:45      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/pascals-triangle/

Given numRows, generate the first numRows of Pascal‘s triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解题思路:

简单的题目,一次AC,中文名:杨辉三角。

思路就是每个元素等于肩膀上两个元素的和,坐标的关系是num[i][j]=num[i - 1][j -1] + num[i - 1][j]。注意第一个元素和最后一个元素,否则下标会越界。

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> resultList = new ArrayList<List<Integer>>();
        for(int i = 0; i < numRows; i++){
            List<Integer> currentList = new ArrayList<Integer>();
            if(i == 0){
                currentList.add(1);
                resultList.add(currentList);
                continue;
            }
            for(int j = 0; j < i + 1; j++){
                if(j == 0){
                    currentList.add(1);
                }else if(j == i){
                    currentList.add(1);
                }else{
                    currentList.add(resultList.get(i - 1).get(j - 1) + resultList.get(i - 1).get(j));
                }
            }
            resultList.add(currentList);
        }
        return resultList;
    }
}

 

 



Pascal's Triangle

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4332758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!