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?
First, let's familiarize ourselves with the characteristics of the Yang Hui triangle:
1. Each number is equal to the sum of the two numbers above it. 2. Each line of numbers is symmetric between the left and right, and gradually increases from 1. 3. There are n numbers in the nth row. 4. The number in line N is 2.
N-1. 5. The number of M in row N is equal to the number of N-m + 1, that is, C (N-1 m-1) = C (n-1, N-m) (One of the composite numbers) 6. Each number is equal to the sum of the left and right digits of the previous row. The entire Yang Hui triangle can be written in this way. That is, the number of I in the n + 1 row is equal to the sum of the number of I-1 in the N row and the number of I, which is also one of the properties of the combination number. That is. 7.
1. The space complexity is O (K2). The Code is as follows. Pay attention to the initialization of the vector two-dimensional array. The number of rows of the Two-dimensional array must be defined:
class Solution {public: vector<int> getRow(int rowIndex) { vector<vector<int>> vec(rowIndex+1); for(int i=0;i<=rowIndex;++i) { vec[i].push_back(1); for(int j=1;j<=i-1;++j) { vec[i].push_back(vec[i-1][j-1]+vec[i-1][j]); } if(i!=0) vec[i].push_back(1); } return vec[rowIndex]; }};2. space complexity O (K), we can use only one array to represent the Yang Hui triangle. When we look back at a line, we can find that the last plus the second to the last is equal to the last one in the next row, and will not update the number we need, so that we can calculate the second to the last in the next row.
The Code is as follows:
class Solution {public: vector<int> getRow(int rowIndex) { vector<int> vec(rowIndex+1,0); int i,j; for (i=0; i<=rowIndex; ++i) { if(i==0) vec[0]=1; else { for (j=i-1; j>=1; --j)
{ vec[j]=vec[j]+vec[j-1]; } vec[i]=1; } } return vec; }};
Pascal's triangle II