题目
给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例
输入: rowIndex = 3
输出: [1,3,3,1]
输入: rowIndex = 0
输出: [1]
输入: rowIndex = 1
输出: [1,1]
解决方案
跟直接组装杨辉三角没有区别,只是不需要加到返回值中、
class Solution {
public List<Integer> getRow(int rowIndex) {
if(rowIndex == 0) {
return Arrays.asList(1);
} else if(rowIndex == 1) {
return Arrays.asList(1,1);
} else {
List<List<Integer>> result = new ArrayList<>();
List<Integer> lastList = Arrays.asList(1,1);
for (int i = 2; i <= rowIndex; i++) {
List<Integer> list = new ArrayList<>();
// 这一行加上第一个1
list.add(1);
// 遍历上一行(index从0到倒数第二个)
for (int j = 0; j < lastList.size() - 1; j++) {
list.add(lastList.get(j) + lastList.get(j+1));
}
// 这一行加上最后一个1
list.add(1);
lastList = list;
}
return lastList;
}
}
}