您的位置:首页 > 其它

LeetCode(30)-Pascal's Triangle

2016-04-07 12:38 393 查看

题目:

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


思路

题意是要用数组表示帕斯卡三角形

输入一个数值,显示相应行数的【帕斯卡三角形

根据下一行和上一行的递推公式来处理

设置一个变量fisrt来记录上一行的数据,最新一行的是新建的

-

代码

public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> all = new ArrayList<List<Integer>>();
List<Integer> first = new ArrayList<Integer>();
if(numRows == 0){
return all;
}
if(numRows == 1){
List<Integer> a1 = new ArrayList<Integer>();
a1.add(1);
all.add(a1);
return all;
}
if(numRows > 1){
List<Integer> a2 = new ArrayList<Integer>();
a2.add(1);
all.add(a2);
}
for(int i = 1;i < numRows;i++){
List<Integer> next = new ArrayList<Integer>();
next.clear();
next.add(1);
for(int a = 1;a < i;a++){
if(a-1 >= 0 )
next.add(first.get(a-1)+first.get(a));
}
next.add(1);
all.add(next);
first.clear();
if(next != null){
for(int o = 0;o < next.size();o++){
first.add(next.get(o));
}
}
}
return all;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: