题目描述
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
解题思路
本题是在上一题Pascal's Triangle的基础上稍作修改而完成的,需要注意的是给定的下标是从零开始的,因此代码在上一题代码的基础上进行了调整。
自己的代码
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
解题思路
本题是在上一题Pascal's Triangle的基础上稍作修改而完成的,需要注意的是给定的下标是从零开始的,因此代码在上一题代码的基础上进行了调整。
自己的代码
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class PascalsTriangleII {
public List<Integer> getRow(int rowIndex) {
rowIndex++;
List<List<Integer>> list = new ArrayList<List<Integer>>();
if(rowIndex <= 0) return null;
else{
for(int times = 1; times <= rowIndex; times++){
if(times == 1) {
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
list.add(tempList);
}
else if(times == 2){
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
tempList.add(1);
list.add(tempList);
}
else{
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
for(int i = 1; i < times-1; i++){
int num = list.get(times-2).get(i) + list.get(times-2).get(i-1);
tempList.add(num);
}
tempList.add(1);
list.add(tempList);
}
}
}
rowIndex--;//System.out.println(rowIndex);
return list.get(rowIndex);
}
public static void main(String[] args) {
PascalsTriangleII pt = new PascalsTriangleII();
//System.out.println(pt.getRow(0).toString());
//System.out.println(pt.getRow(1).toString());
//System.out.println(pt.getRow(2).toString());
//System.out.println(pt.getRow(3).toString());
//System.out.println(pt.getRow(4).toString());
System.out.println(pt.getRow(5).toString());
}
}