Pascal's Triangle
Posted 细雨落花
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章