Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
杨辉三角,解法就是遍历每一层,在上一层的基础上修改值。
e.g:
从第二层到第三层:
{1,3,3,1} -> {1,4,6,4,1} save {3}, replace {3} with {1} + {3} = {4}, save next {3}, replace next {3} with {3} + {3} = {6}, save {1} replace {1} with {3} + {1} = {4}
public class PascalTriangle2 {
public static ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i <= rowIndex; i++) {
int pre = 1;
for (int j = 1; j <= i-1; j++) {
int temp = list.get(j);
list.set(j, pre + temp);
pre = temp;
}
list.add(1);
}
return list;
}
public static void main(String[] args) {
System.out.println(getRow(3));
}
}
或者:
public static ArrayList<Integer> getRow(int rowIndex){
if(rowIndex <0) return new ArrayList<>();
ArrayList<Integer> upper = new ArrayList<>();
upper.add(1);
while(rowIndex > 0){
ArrayList<Integer> lower = new ArrayList<>();
lower.add(1);
for(int i = 1; i < upper.size(); i++){
lower.add(upper.get(i-1) + upper.get(i));
}
lower.add(1);
upper = lower;
rowIndex--;
}
return upper;
}