给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
思路:当 numRows 为 1 或者 2 的时候,值是固定的,分别是[ [1] ],[ [ 1 ] ,[ 1 ,1 ]],而从第三行中间的数是第二行的两数之和
有 ,使用一个数组保存上一行的值,并且使用另外的数组记录下要保存的值。
代码:
class Solution {
public List<List<Integer>> generate(int numRows) {
if(numRows < 0) return null;
List<List<Integer>> list = new ArrayList();
if(numRows >= 1){
List<Integer> data = new ArrayList();
data.add(1);
list.add(data);
}
if(numRows >= 2){
List<Integer> data = new ArrayList();
data.add(1);
data.add(1);
list.add(data);
}
if(numRows >= 3){
for(int i = 3;i <= numRows;i++){
List<Integer> data = new ArrayList();
List<Integer> prev = list.get(i-2);
data.add(1);
for(int j = 2;j <= i-1 ;j++){
data.add(prev.get(j-2) + prev.get(i-1);
}
data.add(1);
list.add(data);
}
}
return list;
}
}
解法二:使用二维数组递归实现,
public static int[][] yanghui(int n) {
if (n == 1) // 递归条件出口
return new int[][] { { 1 } };
if (n == 2) // 递归条件出口
return new int[][] { { 1 }, { 1, 1 } };
// n > 3时的情况
int[][] result = new int[n][];
result[0] = new int[] { 1 };
result[1] = new int[] { 1, 1 };
// 动态计算数组的值
for (int i = 2; i < n; i++) {
result[i] = new int[i + 1];
result[i][0] = 1;
result[i][i] = 1;
for (int j = 1; j < i; j++) {
result[i][j] = result[i - 1][j] + result[i - 1][j - 1];
}
}
return result;
}