I. Question
This question requires a certain line of values in the Yang Hui triangle.
Ii. Analysis
This question is very similar to Pascal 'striangle, but only the result of a Certain Row needs to be obtained here. In Pascal's triangle, because all results are obtained, we need the data of the previous row to be naturally accessible. Here we only need one row of data, so we have to consider whether we can store results with only one row of space instead of storing the last row?
This is indeed feasible. For each row, we know that if we scan back and forth, the value of element I is equal to ans [I] + ans [I + 1] In the previous row. We can see that the data is read forward, if we only use one row of space, the required data will be overwritten. So here the method is to sweep from the back, so that every time the data needed is ans [I] + ans [I-1], the data we need will not be overwritten, because the ANS [I] is only used in the current step, the next step is not required. This technique is also frequently used in Dynamic Planning and saving space. It mainly depends on whether the data we need is the original data or the new data to determine the direction of our traversal. The time complexity is still O (N ^ 2), while the space here is O (k) to store the results, there is still no extra space.
For example, when the number of rows is 5
0: 0 00 0 0
1: 1 00 0 0
2: 1 10 0 1
3: 1 21 0 1
4: 1 33 1 1
5: 1 46 4 1
We can see that the red part is the standard Yang Hui triangle, so it is not difficult to understand the Traversal method from the back to the front.
class Solution {public:vector<int> getRow(int rowIndex) {if (rowIndex < 0) return vector<int>();vector<int> res(rowIndex + 1);if (rowIndex == 0){res[0] = 1;return res;}int t1, t2;for (int i = 1; i <= rowIndex; i++){res[0] = res[i] = 1;t1 = res[0];t2 = res[1];for (int j = 1; j < i; j++){res[j] = t1 + t2;t1 = t2;t2 = res[j + 1];}}return res;}};class Solution {public: vector<int> getRow(int rowIndex) { vector<int> ans(rowIndex+1,1); for(int i=0;i<=rowIndex;i++) { for(int j=i-1;j>=1;j--) { ans[j]=ans[j]+ans[j-1]; } } return ans; }};class Solution {public: vector<int> getRow(int rowIndex) { vector<int> ans; if(rowIndex <0) return ans; ans.push_back(1); for(int i=1;i<=rowIndex;i++) { for(int j=ans.size()-2;j>=0;j--) { ans[j+1]=ans[j]+ans[j+1]; } ans.push_back(1); } return ans; }};
Leetcode: Pascal's _ triangle_ii