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

[LeetCode]118.Pascal's Triangle

时间:2015-02-06 13:18:04      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode   经典面试题   

题目

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

思路

模拟

代码

    /**------------------------------------
    *   日期:2015-02-06
    *   作者:SJF0115
    *   题目: 118.Pascal‘s Triangle
    *   网址:https://oj.leetcode.com/problems/pascals-triangle/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        vector<vector<int> > generate(int numRows) {
            vector<int> row;
            vector<vector<int> > triangle;
            if(numRows >= 1){
                row.push_back(1);
                triangle.push_back(row);
            }//if
            if(numRows >= 2){
                row.push_back(1);
                triangle.push_back(row);
            }//if
            for(int i = 2;i < numRows;++i){
                row.clear();
                row.push_back(1);
                for(int j = 1;j < i;++j){
                    row.push_back(triangle[i-1][j-1]+triangle[i-1][j]);
                }//for
                row.push_back(1);
                triangle.push_back(row);
            }//for
            return triangle;
        }
    };

    int main(){
        Solution s;
        int n = 5;
        vector<vector<int> > result = s.generate(n);
        // 输出
        for(int i = 0;i < result.size();++i){
            for(int j = 0;j < result[i].size();j++){
                cout<<result[i][j]<<"  ";
            }//for
            cout<<endl;
        }//for
        return 0;
    }

运行时间

技术分享

思路二

    /**------------------------------------
    *   日期:2015-02-06
    *   作者:SJF0115
    *   题目: 118.Pascal‘s Triangle
    *   网址:https://oj.leetcode.com/problems/pascals-triangle/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    class Solution {
    public:
        vector<vector<int> > generate(int numRows) {
            vector<vector<int>> triangle(numRows);
            for (int i = 0;i < numRows;++i) {
                triangle[i].resize(i + 1);
                triangle[i][0] = triangle[i][i] = 1;
                for (int j = 1;j < i;++j) {
                    triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
                }//for
            }//for
            return triangle;
        }
    };

运行时间

技术分享

[LeetCode]118.Pascal's Triangle

标签:leetcode   经典面试题   

原文地址:http://blog.csdn.net/sunnyyoona/article/details/43562277

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