首页 > 其他 > 详细

118. 119. Pascal's Triangle -- 杨辉三角形

时间:2016-05-01 11:02:35      阅读:262      评论:0      收藏:0      [点我收藏+]

118.

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]
]
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans;
        if(numRows < 1)
            return ans;
        vector<int> pre, cur;
        pre.push_back(1);
        ans.push_back(pre);
        for(int i = 1; i < numRows; i++)
        {
            cur.push_back(1);
            for(int j = 0; j < pre.size()-1; j++)
            {
                cur.push_back(pre[j]+pre[j+1]);
            }
            cur.push_back(1);
            ans.push_back(cur);
            pre = cur;
            cur.clear();
        }
        return ans;
    }
};

 

119.

Given an index k, return the kth row of the Pascal‘s triangle.

For example, given k = 3,
Return [1,3,3,1].

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

只开一个数组,从后向前计算。

118. 119. Pascal's Triangle -- 杨辉三角形

原文:http://www.cnblogs.com/argenbarbie/p/5450160.html

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