[LeetCode] 119. Pascal's Triangle II
文章目录
Problem
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Solution
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
if (rowIndex < 0) return res;
//rowIndex is zero-based, so from 0 to rowIndex
for (int i = 0; i <= rowIndex; i++) {
res.add(0, 1);
for (int j = 1; j < res.size()-1; j++) {
res.set(j, res.get(j)+res.get(j+1));
}
}
return res;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论