Given an integer numRows
, return the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
解题思路
这道题比较简单,可以递归,也可以直接直接迭代。给出我的递归解法:
class Solution {
public List<List<Integer>> generate(int numRows) {
return generateInRecur(numRows);
}
private List<List<Integer>> generateInRecur(int rows) {
if (rows == 1) {
List<List<Integer>> ret = new ArrayList<>();
ret.add(Collections.singletonList(1));
return ret;
}
List<List<Integer>> allLevels = generateInRecur(rows - 1);
List<Integer> lastLevel = allLevels.get(rows - 2);
List<Integer> curLevel = new ArrayList<>();
curLevel.add(1);
for (int i = 1; i < rows - 1; i++) {
curLevel.add(lastLevel.get(i-1) + lastLevel.get(i));
}
curLevel.add(1);
allLevels.add(curLevel);
return allLevels;
}
}
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付