美文网首页
LeetCode 118. Pascal's Triangle

LeetCode 118. Pascal's Triangle

作者: cb_guo | 来源:发表于2019-02-25 22:37 被阅读0次

题目描述

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:
Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

题目思路

代码 C++

  • 思路一、
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        vector<int> a;
        vector<int> b;
        
        for(int i=1; i <= numRows; i++){
            if(i == 1){
                a.push_back(1);
                result.push_back(a);
            }
            else if(i == 2){
                b.push_back(1);
                b.push_back(1);
                result.push_back(b);
            }
            else{
                a.clear();
                a.push_back(1);
                for(int i=0; i < b.size()-1; i++){
                    a.push_back(b[i]+b[i+1]);
                }
                a.push_back(1);
                result.push_back(a);
                b = a;
            }
        }
        
        return result;
    }
};
  • 思路二、
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result(numRows);
        
        for(int i=0; i < numRows; i++){
            result[i].resize(i+1);
            result[i][0] = result[i][i] = 1;
            
            for(int j=1; j < i; j++){
                result[i][j] = result[i-1][j-1] + result[i-1][j];
            }
        }
        
        return result;
    }
};

总结展望

相关文章

网友评论

      本文标题:LeetCode 118. Pascal's Triangle

      本文链接:https://www.haomeiwen.com/subject/qjbnyqtx.html