Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]<Solution>
這題是要找出 Pascal's triangle,並不困難,直覺的解法就可以了
- 頭和尾一定都是 1
- 中間就是把上一次結果的 index-1 和 index 的值相加得出目前 index 的值
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, 1)); | |
for(int j = 1; j < i; j++) { | |
ans[i][j] = ans[i-1][j-1] + ans[i-1][j]; | |
} | |
} | |
return ans; | |
} | |
}; |
沒有留言:
張貼留言