Pascal's Triangle

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)