码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】118. Pascal's Triangle

时间:2015-07-23 22:00:24      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:leetcode   pascaltri   simulation   

@requires_authorization
@author johnsondu
@create_time 2015.7.23 19:54
@url [Pascal‘s Triangle](https://leetcode.com/problems/pascals-triangle/)
/************************
 * @description: simple.
 * @time_complexity:  O(n)
 * @space_complexity: O(n)
 ************************/
 class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans;

        for(int i = 1; i <= numRows; i ++) {
            vector<int> layer;
            if(i == 1) layer.push_back(1);
            else {
                for(int j = 1; j <= i; j ++) {
                    if(j == 1 || j == i)  layer.push_back(1);
                    else layer.push_back(ans[i-2][j-2] + ans[i-2][j-1]);
                }
            }
            ans.push_back(layer);
        }
        return ans;
    }
};
@requires_authorization
@author johnsondu
@create_time 2015.7.23 19:54
@url [Pascal‘s Triangle](https://leetcode.com/problems/pascals-triangle/)
/************************
 * @description: simple.
 * @time_complexity:  O(n)
 * @space_complexity: O(n)
 ************************/
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans;
        if(numRows < 1) return ans;

        vector<int> first;
        first.push_back(1);
        ans.push_back(first);
        if(numRows < 2) return ans;

        vector<int> second;
        second.push_back(1);
        second.push_back(1);
        ans.push_back(second);

        for(int i = 3; i <= numRows; i ++) {
            vector<int> layer;
            layer.push_back(1);
            for(int j = 0; j < ans[i-2].size()-1; j ++) {
                layer.push_back(ans[i-2][j] + ans[i-2][j+1]);
            }
            layer.push_back(1);
            ans.push_back(layer);
        }
        return ans;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】118. Pascal's Triangle

标签:leetcode   pascaltri   simulation   

原文地址:http://blog.csdn.net/zone_programming/article/details/47027357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!