Array:Pascal's 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] ]
杨辉三角,给出行数,生成该行数的杨辉三角
一种解法:
public class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> allrows = new ArrayList<List<Integer>>(); ArrayList<Integer> row = new ArrayList<Integer>(); for(int i=0;i<numRows;i++) { row.add(0, 1); for(int j=1;j<row.size()-1;j++) row.set(j, row.get(j)+row.get(j+1)); allrows.add(new ArrayList<Integer>(row)); } return allrows; } }
例 i = 5的生成过程:
i = 0
row = [1]; 内层循环不执行; allrows = [[1]];
i = 1;
row = [1,1];内层循环不执行; allrows = [[1], [1, 1]];
i = 2;
row = [1, 1, 1];
j = 1; row[1] = row.get(1) + row.get(2); row = [1, 2, 1];
allrows = [[1], [1, 1], [1, 2, 1]];
i = 3;
row = [1, 1, 2, 1];
j = 1; row = [1, 3, 2, 1]; j = 2; row = [1, 3, 3, 1];
allrows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]];
i = 4;
row = [1, 1, 3, 3, 1];
j = 1; row = [1, 4, 3, 3, 1]; j = 2; row = [1, 4, 6, 3, 1]; j = 3; row = [1, 4, 6, 4, 1];
allrows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]];
row.add(0,1)是在数组的开始,即下标为0的位置插入元素1,其他元素后移一位。
Pascal's Triangle II
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
给出行数,返回杨辉三角第k行的值
public class Solution { public List<Integer> getRow(int rowIndex) { ArrayList<Integer> row = new ArrayList<Integer>(); if (rowIndex < 0) return row; for (int i = 0; i < rowIndex + 1; i++) { row.add(0,1); for (int j = 1; j < row.size() - 1; j++) { row.set(j, row.get(j) + row.get(j + 1)); } } return row; } }