leecode2 杨辉三角
1.背景知识
-
什么是ArrayList
ArrayList就是传说中的动态数组,用MSDN中的说法,就是Array的复杂版本,它提供了如下一些好处:
动态的增加和减少元素
实现了ICollection和IList接口
灵活的设置数组的大小 -
如何使用ArrayList
-
最简单的例子:
class Solution {
public:
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> last=new ArrayList<Integer>;
last.add(1);
if(rowIndex==0){
return last;
}
for(int i;i<rowIndex;i++){
ArrayList<Integer> tmp=new ArrayList<Integer>;
tmp.add(1);
for(int j;j<i;j++){
tmp.add(last.get(j),last.get(j-1));
}
tmp.add(1)
last=tmp;
return last;
}
}
};
但是好像不能通过.(我是看的别人的博客仿照的哇。。。。哇的哭啦。。。??
于是我决定重新开始使用 # vector #
class Solution {
public:
vector<int> getRow(int rowIndex){
vector<int> res;
res.push_back(1);
vector<int> col;
for(int i=1;i<=rowIndex;i++){
col.push_back(1);
for(int j=1;j<i;j++){
col.push_back(res[j-1]+res[j]);
}
col.push_back(1);
res=col;
col.clear();
}
return res;
}
};
AC啦!!!
思考:我这次的感悟是 vector很灵活,2维的数组可以像拼拼图一样可以把东西拼好~vector是手段~ c++是面向对象的!