LeetCode 119 Pascal & #39; s Triangle II (Pascal Triangle II) (vector, mathematical formula )(*)
Translation
Given an index K, return the K row of the Pascal triangle. For example, if K is 3, [1, 3, 3] is returned. Note: can you improve your algorithm to only use the extra space of O (k?
Original
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
This question is actually taken over by the previous question, and I just finished writing it.
LeetCode 118 Pascal's Triangle (Pascal Triangle) (vector)
The previous question is to return the complete Pascal triangle:
class Solution {public: vector
> generate(int numRows) { vector
> pascal; if (numRows < 1) return pascal; vector
root; root.push_back(1); pascal.push_back(root); if (numRows == 1) return pascal; root.push_back(1); pascal.push_back(root); if (numRows == 2) return pascal; if (numRows > 2) { for (int i = 2; i < numRows; ++i) { vector
temp; temp.push_back(1); for (int j = 1; j < pascal[i - 1].size(); ++j) { temp.push_back(pascal[i - 1][j - 1] + pascal[i - 1][j]); } temp.push_back(1); pascal.push_back(temp); } return pascal; } }};
So I am a little lazy. Since it is an index K, it is better to return it, but the efficiency is ......
class Solution {public: vector
getRow(int rowIndex) { rowIndex += 1; vector
> pascal; if (rowIndex < 1) return pascal[0]; vector
root; root.push_back(1); pascal.push_back(root); if (rowIndex == 1) return pascal[0]; root.push_back(1); pascal.push_back(root); if (rowIndex == 2) return pascal[1]; if (rowIndex > 2) { for (int i = 2; i < rowIndex; ++i) { vector
temp; temp.push_back(1); for (int j = 1; j < pascal[i - 1].size(); ++j) { temp.push_back(pascal[i - 1][j - 1] + pascal[i - 1][j]); } temp.push_back(1); pascal.push_back(temp); } return pascal[rowIndex - 1]; } }};
A more efficient way should be to have a certain formula. Let's see what others have written ......
vector
getRow(int rowIndex) { vector
r; r.resize(rowIndex + 1); r[0] = r[rowIndex] = 1; for (auto i = 1; i < (r.size() + 1) / 2; ++i) { r[i] = r[rowIndex - i] = (unsigned long)r[i - 1] * (unsigned long)(rowIndex - i + 1) / i; } return r;}
Sure enough, the power of mathematics appeared again. Let me use the Markdown syntax to write this formula ......
Ri = ri? 1? (Index? I + 1)/I