[Leetcode 36] 119 Pascal's Triangle II
2013-05-24 06:27
169 查看
Problem:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Note:
Could you optimize your algorithm to use only O(k) extra space?
Analysis:
The direct way to solve the problem is to use the formula: C(i, k) = k! / (i! * (k-i)!). But it will exceed the int number range if k is very large.
So we have to use the iterative way to construct the answer: to compute kth row, we first compute (k-1)th row and then use it to construct the desired row.
Code:
View Code
Attention:
Notice to add a new element into tmp, use push_back, not [].
The inner loop's max value is i not rowIndex.
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
Analysis:
The direct way to solve the problem is to use the formula: C(i, k) = k! / (i! * (k-i)!). But it will exceed the int number range if k is very large.
So we have to use the iterative way to construct the answer: to compute kth row, we first compute (k-1)th row and then use it to construct the desired row.
Code:
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res; res.push_back(1); if (rowIndex == 0) return res; res.push_back(1); if (rowIndex == 1) return res; for (int i=1; i<rowIndex; i++) { vector<int> tmp; tmp.push_back(1); for (int j = 1; j <= i; j++) { tmp.push_back(res[j-1] + res[j]); } tmp.push_back(1); res = tmp; } return res; } };
View Code
Attention:
Notice to add a new element into tmp, use push_back, not [].
The inner loop's max value is i not rowIndex.
相关文章推荐
- Leetcode[119]-Pascal's Triangle II
- [LeetCode] 119: Triangle
- 【leetcode】【36】Valid Sudoku
- [Leetcode 36, easy] Valid Sudoku
- [leetCode]119.Pascal's Triangle II
- leetcode 119 Pascal's Triangle II C++
- LeetCode 119. Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- 2017.11.14 LeetCode - 118. Pascal's Triangle - 119. Pascal's Triangle II
- leetcode-36-valid sudoku
- Leetcode 119 Pascal's Triangle II
- 36_leetcode_Count and Say
- 【LeetCode】36 - Valid Sudoku
- LeetCode 36 Populating Next Right Pointers in Each Node
- Leetcode: 36. Valid Sudoku
- leetcode 36: Valid Sudoku
- LeetCode 119. Pascal's Triangle II
- LeetCode-Array-119. Pascal's Triangle II
- LeetCode 36. Valid Sudoku
- 【一天一道LeetCode】#119. Pascal's Triangle II