1. 程式人生 > >LeetCode | Pascal's Triangle(楊輝三角)

LeetCode | Pascal's 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]
]

題目解析:

方案一:

一行一行生成,每一行首先要放入一個元素1,然後後面的元素是上一層的兩個元素的和,最後也要放入一個1。

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<int> tmp;
        if(numRows == 0)
            return res;

        tmp.push_back(1);
        res.push_back(tmp);
        while(numRows > 1){
            numRows--;
            tmp = GenerateSub(tmp);
            res.push_back(tmp);
        }
        return res;
    }
    vector<int> GenerateSub(vector<int> arr){
        vector<int> tmp;
        tmp.push_back(1);

        int n = arr.size();
        for(int i = 0;i < n-1;i++){
            tmp.push_back(arr[i]+arr[i+1]);
        }
        tmp.push_back(1);
        return tmp;
    }
private:
    vector<vector<int> > res;
};


方案二:

容器的容器,可以看成一個二維陣列,當然不是完整的,每一行的元素個數不一樣。但能像二維陣列一樣去引用每一個元素。

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<vector<int>> ans;
        for(int i = 0;i < numRows;i++)
        {
            vector<int> cur;
            if(i == 0)
                cur.push_back(1);
            else
            {
                for(int j = 0;j <= i;j++)
                {
                    if(j == 0 || j == i) cur.push_back(1);
                    else cur.push_back(ans[i - 1][j] + ans[i - 1][j - 1]);
                }
            }
            ans.push_back(cur);
        }
        
        return ans;
    }
};