[LeetCode]第二十题 :帕斯卡三角

题目描述:

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

题目解释:

给出一个数字,求出来这个数字高度的帕斯卡三角。

题目解法:

1.我的解法:我的解法相对来说比较low,帕斯卡三角的特点是每一层的节点数等于层数,开始和结尾的数字都是1,中间的数字是上一层相邻两个数组的和,所以我利用这一特点进行求解。用一个中间数组记录上一层的值,当下标等于1的时候将值设置为1,当下标是层数的时候设置值为1,当下标不为这两种情况时利用中间数组求值。代码如下:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList();
        if(numRows < 1) return result;
        int[] tempArray = new int[numRows]; 
        for(int i = 1;i <= numRows;i++) {
            List<Integer> list= new ArrayList();
            for(int j = 1; j <= i;j++) {
                if(j == 1) list.add(1);
                else if(j == i) list.add(1);
                else {
                    int temp = tempArray[j - 2] + tempArray[j - 1];
                    list.add(temp);
                }  
            }
            for(int k = 0;k < list.size();k++) {
                tempArray[k] = list.get(k);
            }
            result.add(list);
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80928430