给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
由于和118题很相似,就直接套了下118的源代码如下
class Solution {
public List<Integer> getRow(int rowIndex) {
int numRows = rowIndex+1;
List<List<Integer>> list = new ArrayList<>();
if (rowIndex == 0) {
ArrayList arrList = new ArrayList();
arrList.add(1);
return arrList;
}
if (rowIndex == 1) {
ArrayList arrList = new ArrayList();
arrList.add(1);
arrList.add(1);
return arrList;
}
// 开始初始化并创建杨辉三角
// list.add((ArrayList)arr);
for (int i = 0; i <= numRows; i++) {
ArrayList arrayList = new ArrayList();
arrayList.add(1); // 初始化第一位 下标 0 位
list.add(arrayList); // 将整个数组添加进去 后面要用到
if(i==1){ // 从 第3 行 开始进行加和 所以 第二行 即下标 1 的行 要保证有两个数 1
arrayList.add(1);
}
if (i >= 2) {
for (int j = 1; j < i; j++) {
arrayList.add(list.get(i - 1).get(j - 1) + list.get(i - 1).get(j));
}
arrayList.add(1);
}
}
return list.get(numRows - 1);
}
}
上面写的有些粗糙, 可以不用保存那么多 数组, 只需要两个就足够了,下面是借鉴了一些人的写法。
使用两个列表 从头开始
public List<Integer> getRow(int rowIndex) {
List<Integer> pre = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
for (int i = 0; i <= rowIndex; i++) {
cur = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
cur.add(1);
} else {
cur.add(pre.get(j - 1) + pre.get(j));
}
}
pre = cur;
}
return cur;
}
/*
作者:windliang
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--28/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
另一种是 从尾部开始
public List<Integer> getRow(int rowIndex) {
int pre = 1;
List<Integer> cur = new ArrayList<>();
cur.add(1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--) {
cur.set(j, cur.get(j - 1) + cur.get(j));
}
cur.add(1);//补上每层的最后一个 1
}
return cur;
}
/*
作者:windliang
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--28/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
当然还有一种比较厉害的想法
虽然自己也想到了 不过耐克执行能力。。。
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<>();
if (rowIndex == 0) {
result.add(1);
return result;
}
if (rowIndex == 1) {
result.add(1);
result.add(1);
return result;
}
result.add(1);
result.add(1);
for (int i = 1; i < rowIndex; i++) {
result.add(1);
for (int j = 0; j < i; j++) {
result.add(result.get(0) + result.get(1));
result.remove(0);
}
result.add(1);
result.remove(0);
}
return result;
}
/*
作者:mirror-12
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/zhi-xing-yong-shi-2-ms-zai-pascals-triangle-iide-j/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
解决思路是:
从第二行 1 2 1 说起:
当 rowIndex == 2 时,
result.add(1);
当前 保留值 为 1 1 1;
执行:
for (int j = 0; j < i; j++) {
result.add(result.get(0) + result.get(1));
result.remove(0);
}
得到结果为: 1 1 2
result.add(1);
result.remove(0);
然后结果: 1 2 1
后面 rowIndex == 3也是如此 往前移位 然后进行累加。