首页 > 其他 > 详细

LeetCode (13) Pascal's Triangle (杨辉三角 )

时间:2015-04-18 23:49:03      阅读:435      评论:0      收藏:0      [点我收藏+]

题目描述

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return
技术分享

从第三行开始,每行除了最左边和最右边两个数为1,其他数字都是上一行中相邻两个数字之和。根据上述规则可以写出下面的代码:

class Solution {
public:
    vector<vector<int> > generateRow1() {
        vector<int> row;
        row.push_back(1);
        vector<vector<int>> r;
        r.push_back(row);
        return r;
    }

    vector<vector<int> > generateRow2() {
        vector<vector<int>> r = generateRow1();
        vector<int> row;
        row.push_back(1);
        row.push_back(1);
        r.push_back(row);
        return r;
    }
    vector<vector<int> > generate(int numRows) {
        if (numRows < 1)
        {
            vector<vector<int> > r;
            return r;
        }

        if (numRows == 1)
            return generateRow1();
        if (numRows == 2)
            return generateRow2();

        vector<vector<int> > r = generateRow2();
        for (int i = 2; i != numRows; ++i)
        {
            vector<int> row;
            row.push_back(1);
            for(int j = 1; j != i; ++j)
            {
                int next = r[i-1][j-1] + r[i-1][j];
                row.push_back(next);
            }
            row.push_back(1);
            r.push_back(row);
        }
        return r;
    }
};

LeetCode (13) Pascal's Triangle (杨辉三角 )

原文:http://blog.csdn.net/angelazy/article/details/45117061

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