目標是要產生如下的數列:
[]
[1]
[1 1]
[1 2 1]
[1 3 3 1]
[1 4 6 4 1]
[1 5 10 5 1]
以上還可再細分成下:
[]
[1]
[1]
[11]
[1 1]
[11 1]
[1 2 1]
[11 2 1]
[1 3 3 1]
[11 3 3 1]
[1 4 6 4 1]
[11 4 6 4 1]
[1 5 10 10 5 1]

於是程式可寫成如下:
public class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> pascal = 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)); pascal.add(new ArrayList<Integer>(row)); } return pascal; } }
沒有留言:
張貼留言