#Problem description:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Note that the row index starts from 0.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Could you optimize your algorithm to use only O(k) extra space?

#Solution:

  1. Init an array with size of rowIndex+1.
  2. Increment the value from the end to beginning.
1
2
3
4
5
6
7
8
9
10
11
Init:
---------------------
1 0.... 0

i=1:
---------------------
1 1 0.... 0

i=2:
---------------------
1 2 1 0.... 0
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> getRow(int rowIndex) {

vector<int> A(rowIndex+1, 0);
A[0] = 1;
for(int i=1; i<rowIndex+1; i++)
for(int j=i; j>=1; j--)
A[j] += A[j-1];
return A;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0: return [1]
if rowIndex == 1: return [1, 1]
list = [[] for i in range(rowIndex+1)]
list[0] = [1]
list[1] = [1, 1]
for i in range(2, rowIndex+1):
list[i] = [1 for j in range(i + 1)]
for j in range(1, i):
list[i][j] = list[i - 1][j - 1] + list[i - 1][j]
return list[rowIndex]

reference:
https://goo.gl/4Nkj1c