Leetcode Note: Pascal & #39; s Triangle II
I. Description
Given an indexk, ReturnkTh row of the Pascal's triangle.
For example, givenk = 3,
Return[1,3,3,1].
Note:
Cocould you optimize your algorithm to use onlyO(k)Extra space?
Ii. Question Analysis
For the definition of Pascal triangle, see: http://baike.baidu.com/link? Url = qk _-urYQnO4v6v3P4BuMtCa0tMNUqJUk4lmbkb1aqbqikBU-ndiMlTF20fq2QUjTTFTeTohZ72KFxgBnz4sJha
This question requires that only the element value of row k be output, and the spatial complexity isO(k)Therefore, only one fixed-length array is used to store the element values of each row. For each new row, the original row can be scanned from the back to the front, there are three main situations:
The last element is directly equal to 1. For intermediate elements whose subscript is I, there are:
result[i] = result[i-1] + result[i]; The first element is directly equal to 1;
In this way, you only needO(k).
Iii. Sample Code
class Solution {public: vector
getRow(int rowIndex) { vector
result(rowIndex + 1); result[0] = 1; if (rowIndex < 1) return result; for(int i = 1; i <= rowIndex; ++i) for(int j = i; j >= 0; --j) if (j == i || j == 0) result[j] = 1; else result[j] = result[j-1] + result[j]; return result; }};
Iv. Summary
If notO(k)The space complexity of the question is lower, but there is no skill at all.