LeetCode 118. Pascal's Triangle

题目描述

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> generate(int numRows) {
        vector> result;
        vector a;
        vector 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> generate(int numRows) {
        vector> 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)