p118

LeetCode p118 Pascal’s Triangle 题解

1.题目:

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]
]

题意:

按规律搭一个塔。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (numRows == 0)
return ans;
List<Integer> first = new ArrayList<Integer>();
first.add(1);
ans.add(first);

for (int i = 1; i < numRows; i++) {
int t = i - 1;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
int a = 0;
for (int j = 0; j < i - 1; j++) {
list.add(ans.get(t).get(a) + ans.get(t).get(a + 1));
a++;
}
list.add(1);
ans.add(list);
}
return ans;
}
}

4.一些总结: