当前位置:编程学习 > C/C++ >>

[LeetCode] Pascal's Triangle

Given numRows, generate the first numRows of Pascal's 易做图.
 
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<vector<int> > generate(int numRows) {  
        // Note: The Solution object is instantiated only once and is reused by each test case.  
        if(numRows == 0)  
            return vector<vector<int> >(0);  
  
        vector<vector<int> > ivec;  
        int i = 0, j = 0;  
        for(i = 0; i < numRows; i++) {  
            vector<int> 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;  
    }  
};  

 


补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,