Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解题思路
观察题目,其实这不就是杨辉三角嘛,边界为1,其他的数计算就是 上一层临近的两个值相加,这个题我想到的解决方案有三种。
- 看成二维数组, 边界设为1,其他的按照上一层临近的值相加就行。
- dfs,观察发现 它是斐波那契数列 递推关系就是f*(i,j)=f(i−1,j−1)+f(i−1,j)*, dfs 深搜求解(我寻思这是一道标着简单的题 以为规模会很小)没考虑时间,其实通过对每一个点进行dfs时间复杂度高, 数据规模大时栈溢出
- 解决递归的重复计算的问题,记忆化计算过程 使用动态规划也可以根据方程f*(i,j)=f(i−1,j−1)+f(i−1,j)*就行
解题代码
第一次写的时dfs的方法(超时:14/15 passed 最后一个数据比较 大就过不去了 Last executed input:30)
class Solution {
public List<List<Integer>> generate(int numRows) {
if (numRows <= 0) return new ArrayList<List<Integer>>();
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < numRows; i++){
List<Integer> sublist = new ArrayList<>();
for (int j = 0; j <= i; j++)
sublist.add(dfs(i, j));
list.add(sublist);
}
return list;
}
public int dfs(int x , int y){
if (x == y || y == 0) return 1;
return dfs(x - 1, y - 1) + dfs(x - 1, y);
}
}
刚刚dfs 其实有这种递推关系的dfs就应该想到了动态规划,其实就是斐波那契数列,换一个形式而已,看过509题就应该有这个想法了吧。没过去那就dp呗 根据关系式f(i,j)=f(i−1,j−1)+f(i−1,j)。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> dp(numRows);
for (int i = 0; i < numRows; i++) {
dp[i].resize(i + 1);
dp[i][i] = dp[i][0] = 1;
for (int j = 1; j < i; j++)
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
return dp;
}
};
换了个思路,其实这个应该是最容易想到的,类似于二维数组 多添加一个list 集合pre保存上一层的值
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> sublist, pre = null;
for (int i = 0; i < numRows; i++) {
sublist = new ArrayList<>();
for (int j = 0; j <= i; j++)
sublist.add(j == 0 || i == j ? 1 : pre.get(j-1) + pre.get(j));
list.add(pre = sublist);
}
return list;
}
}