您的位置:首页 > 其它

[LeetCode] Pascal's Triangle

2014-11-03 13:23 369 查看
class Solution {
public:
vector<vector<int> > result;
vector<vector<int> > generate(int numRows) {
result.clear();
vector<int> v;
for(int i = 0;i < numRows;i ++){
if(i == 0){
v.push_back(1);
result.push_back(v);
}else{
v.clear();
v.push_back(1);
for(int j = 1;j < i && i > 1;j ++){
v.push_back(result[i - 1][j - 1] + result[i - 1][j]);
}
v.push_back(1);
result.push_back(v);
}
}
return result;
}
};

java版

public class Solution {
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0)
return result;
for (int i = 0; i < numRows; i++) {
List<Integer> current = new ArrayList<Integer>();
if (i == 0) {
current.add(1);
result.add(current);//这里要注意下,add进去的是传引用的,所以每次add进去的current都要new一个,不能用同一个变量,否则会覆盖
} else {

current.add(1);
List<Integer> pre = result.get(i - 1);
for (int j = 1; j < i && i > 1; j++) {
current.add(pre.get(j - 1) + pre.get(j));
}
current.add(1);
result.add(current);
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: