当前位置:网站首页>Leetcode notes 118. Yang Hui triangle

Leetcode notes 118. Yang Hui triangle

2022-07-28 13:24:00 Lyrig~

Leetcode note 118. Yang hui triangle

Title Description

Topic linking

Given a nonnegative integer numRows, Generate 「 Yang hui triangle 」 Before numRows That's ok .

stay 「 Yang hui triangle 」 in , Each number is the sum of the numbers at the top left and right of it .

Example 1:

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

Input : numRows = 1
Output : [[1]]

Tips :

1 <= numRows <= 30

Ideas

It's simulation , Pay attention to recurrence relationship a n s [ i ] [ j ] = a n s [ i − 1 ] [ j − 1 ] + a n s [ i − 1 ] [ j ] ( j ! = 0 ∣ ∣ i ) a n s [ i ] [ j ] = 1 ( j = 0 ∣ ∣ i ) \mathcal{ans[i][j]} = ans[i - 1][j - 1] +ans[i-1][j](j!=0 ||i)\\ ans[i][j]=1(j = 0 ||i) ans[i][j]=ans[i1][j1]+ans[i1][j]j!=0∣∣ians[i][j]=1(j=0∣∣i)

among ans[i][j] Means Yang Hui triangle No i Xing di j individual

Code

class Solution {
    
public:
    vector<vector<int>> generate(int numRows) {
    
        vector<vector<int>> ans;

        for(int i = 0; i < numRows; ++ i)
        {
    
            ans.push_back(vector<int>(i + 1));
            for(int j = 0; j < i + 1; ++j)
            {
    
                if(j == 0 || j == i)
                {
    
                    ans[i][j] = 1;
                }
                else ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];
            }
        }
        return ans;
    }
};
原网站

版权声明
本文为[Lyrig~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/209/202207281206596598.html