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

LeetCode118:Pascal's Triangle

时间:2015-12-18 10:40:02      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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]
]

Subscribe to see which companies asked this question

//解题思路:利用一个中间vector来保存每层的数
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> ans;
        for(int i = 0;i < numRows;i++)
        {
            vector<int> cur;
            if(i == 0)
                cur.push_back(1);
            else
            {
                for(int j = 0;j <= i;j++)
                {
                    if(j == 0 || j == i) cur.push_back(1);
                    else cur.push_back(ans[i - 1][j] + ans[i - 1][j - 1]);
                }
            }
            ans.push_back(cur);
        }
        
        return ans;
    }
};

技术分享

LeetCode118:Pascal's Triangle

标签:

原文地址:http://blog.csdn.net/geekmanong/article/details/50349571

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