首页 > 其他 > 详细

Pascal's Triangle I, II

时间:2015-04-16 06:42:26      阅读:243      评论:0      收藏:0      [点我收藏+]

题目链接

https://leetcode.com/problems/pascals-triangle/

https://leetcode.com/problems/pascals-triangle-ii/

 

这两道题都是数组操作,需要注意的是II在I的基础上使用滚动数组存储过往的中间结果,这个思想可以注意一下,一些DP的题目也会用到

 

I‘s code

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > res(numRows, vector<int>(1, 1));
        for(int i = 1; i < numRows; i++) {
            for(int j = 1; j <= i; j++) {
                if(res[i - 1].size() > j)
                    res[i].push_back(res[i - 1][j - 1] + res[i - 1][j]);
                else
                    res[i].push_back(res[i - 1][j - 1]);
            }
        }
        return res;
    }
};

 

II‘s code

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex + 1, 0);
        res[0] = 1;
        for(int i = 1; i <= rowIndex; i++) {
            for(int j = i; j > 0; j--) {
                res[j] = res[j - 1] + res[j];
            }
        }
        return res;
    }
};

 

Pascal's Triangle I, II

原文:http://www.cnblogs.com/walcottking/p/4430838.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!