设为首页 加入收藏

TOP

[LeetCode] Pascal's Triangle
2015-11-21 01:51:34 来源: 作者: 【 】 浏览:9
Tags:LeetCode Pascal' Triangle
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]
]?
?
问题描述:给定一个整数numRows,生成Pascal三角形的前numRows行。
将该三角形的左边对齐,就能够发现,tri[i][j] = tri[i-1][j-1] + tri[i-1][j]。
?
class Solution {  
public:  
    vector > generate(int numRows) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
        if(numRows == 0)  
            return vector >(0);  
  
        vector > ivec;  
        int i = 0, j = 0;  
        for(i = 0; i < numRows; i++) {  
            vector vec;  
            for(j = 0; j < i+1; j++) {  
                if(j == 0 || j == i)  
                    vec.push_back(1);  
                else  
                    vec.push_back(ivec[i-1][j-1] + ivec[i-1][j]);  
            }  
            ivec.push_back(vec);  
        }  
        return ivec;  
    }  
};  

?


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ2528:Mayor's posters(线.. 下一篇 (字符串的模式匹配4.7.8)UVA 100..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: