1. 题目: Kth Row of Pascal’s Triangle
此处有关于该问题的类似解法。
Given an index k, return the kth row of the Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Input : k = 3
Return : [1,3,3,1]
NOTE : k is 0 based. k = 0, corresponds to the row [1].
Note:Could you optimize your algorithm to use only O(k) extra space?输入为第k行,输出改行的元素值(k是从0开始的下标)。
2. 解题思路
1). 法1
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> result = new ArrayList<>();
if (rowIndex < 0)
return result;
result.add(1);
for (int i = 1; i <= rowIndex; i++) {
// 当前循环的result可由上一层循环的result得到
for (int j = result.size() - 2; j >= 0; j--) {
result.set(j + 1, result.get(j + 1) + result.get(j));
}
result.add(1);
}
return result;
}
2). 法2
/*
* C(line, i) = line! / ( (line-i)! * i! ) C(line, i-1) = line! / ( (line -
* i + 1)! * (i-1)! ) We can derive following expression from above two
* expressions. C(line, i) = C(line, i-1) * (line - i + 1) / i
*
* So C(line, i) can be calculated from C(line, i-1) in O(1) time
*/
public ArrayList<Integer> getRow1(int A) {
ArrayList<Integer> list = new ArrayList<Integer>(A + 1);
int line = A + 1;
int C = 1; // used to represent C(line, i)
for (int i = 1; i <= line; i++) {
list.add(C); // The first value in a line is always 1
C = C * (line - i) / i;
}
return list;
}