题目
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
代码模板:
class Solution {
public List<Integer> getRow(int rowIndex) {
}
}
分析
这里要做到最简洁的话,翻阅了很多资料去整理杨辉三角形里面第n+1行m+1个数是怎么得到的,结果发现是n*(n-1)…(n-m)/(1* 2*…*m)
解答
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<>();
long num=1;
for(int i = 0;i <= rowIndex;i ++){
result.add((int)num);
num = num*(rowIndex-i)/(i+1);
}
return result;
}
}