解法一:(动态规划)①定义:dp[i][j]表示下标为ij的数的值,dp[m][n] ②初始状态:dp[0][j]=1;dp[i][last]=1 ③状态转移方程:dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
class Solution {
public List<List<Integer>> generate(int numRows) {
LinkedList<List<Integer>> result = new LinkedList<>();
if (numRows == 0) {
return result;
}
for (int i = 0; i < numRows; i++) {
List<Integer> row = new LinkedList<>();
if (i == 0) {
row.add(1);
}
else {
row.add(1);
for (int j = 1; j < i; j++) {
row.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
}
row.add(1);
}
result.add(row);
}
return result;
}
}
注意:
- 中间的数等于上面两个数之和,要用
j<i
来判断,而不是j<i-1
:for (int j = 1; j < i; j++)