leetcode Pascal's Triangle

Pascal's Triangle

  Total Accepted: 18780  Total Submissions: 59362 My Submissions

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

Have you been asked this question in an interview?  Yes

Discuss

杨辉三角,这个规律写下来,不是很难,注意开头结尾不同就行了。

//10:06 ->10:13 ->10:16
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int> > res;
        if(numRows==0)
        {
            return res;
        }
        vector<int> row1(1,1);
        res.push_back(row1);
        for(int i=1;i<numRows;i++)
        {
            vector<int> row2(i+1,0);
            for(int j=0;j<=i;j++)
            {
                if(j==0)
                {
                    row2[j] = res[i-1][j]; // for the i-1
                }else if(j==i)
                {
                    row2[j] =  res[i-1][j-1];
                }else //add from the j and j-1
                {
                    row2[j] = res[i-1][j-1] + res[i-1][j];
                }
            }
            res.push_back(row2);
        }
        return res;
    }
};


你可能感兴趣的:(LeetCode)