1. 程式人生 > >[LeetCode]118. Pascal's Triangle

[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]
]

題目解析: 帕斯卡三角,又稱楊輝三角,給定一個行數,結合楊輝三角的性質,輸出楊輝三角。
楊輝三角的性質為:每個數字等於上一行的左右兩個數字之和。可用此性質寫出整個楊輝三角。即第n+1行的第i個數等於第n行的第i-1個數和第i個數之和

思路:利用雙重for迴圈來列印楊輝三角,當傳入的numRows不等於0時,則列印的楊輝三角一定包含陣列{1},所以for迴圈跳過第0個數組,從1開始,宣告一個用來快取陣列cur,cur用來生成第i行的陣列,而第i行陣列的資料個數與行數i有關,所以再次定義一個for迴圈,用來生成第i行陣列中的資料,當j=0時,和j=i時,填充的資料都為1,而中間的資料則是等於第i-1行的j-1個數據和第j個數據之和。當內部for迴圈結束後,將其加入res陣列中。最後返回res.

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
       
        vector<vector<int>> res;
         if(numRows==0)return res;
        else res.push_back({1});
        for(int i=1;i!=numRows;i++)
        {
            vector<int> cur;
            //cur.push_back(1);
            for(int j=0;j<=i;j++)
            {
                if(j==0)
                {
                    cur.push_back(res[i-1][0]);
                }
                else if(j==i)cur.push_back(res[i-1][i-1]);
                else cur.push_back(res[i-1][j-1]+res[i-1][j]);
            
            }
            res.push_back(cur);
        }
        return res;
    }
};