Question
Given an index k, return the kth row of the Pascal’s triangle.
For example:
given k = 3,
Return [1,3,3,1].
Note:
optimize your algorithm to use only O(k) extra space.
Idea
给定一个系数k,返回Pascal三角的第k行,将优化算法,使得算法的空间复杂度为O(k).
- 同LeetCode-118,直接使用Pascal三角的生成方式进行解题.
- 该题较118更为简单,无需要对Pascal三角的结构进行存储,仅需依次生成行至所需的行数即可;
- 使用
ArrayList<Integer>存储行.
Code
ArrayList—Java
public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> row = new ArrayList<Integer>();
for (int i=0; i<rowIndex+1; i++){
row.add(0,1);
for(int j=1; j<row.size()-1;j++){
row.set(j, row.get(j)+row.get(j+1));
}
}
return row;
}
}
- 虽然该题较118更为简单,但是依然需要注意,需要返回的是第k行,这里第0行为[1].
- 空间复杂度:O(n)

本文介绍如何求解帕斯卡三角形的第K行,通过优化算法达到O(K)的空间复杂度。使用ArrayList存储行,只需生成到所需行数即可。
877

被折叠的 条评论
为什么被折叠?



