Pascal's Triangle II
2017-01-07 03:14
239 查看
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Note:
Could you optimize your algorithm to use only O(k) extra space?
有一种只需要开辟一个数组的解法,有时间补上。
这道题的思路跟第一问很像,一种解决思路是使用两个数组,pre, cur 不断的更新。
代码:
还有一种解法:只需要一个数组
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if(rowIndex <0){
return list;
}
for(int i=0;i<rowIndex+1;i++){
//首位的1
list.add(0,1);
for(int j=1;j<list.size()-1;j++){
list.set(j, list.get(j)+list.get(j+1));
}
//末尾的1就不动它
}
return list;
}
For example, given k = 3,
Return
[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
有一种只需要开辟一个数组的解法,有时间补上。
这道题的思路跟第一问很像,一种解决思路是使用两个数组,pre, cur 不断的更新。
代码:
public List<Integer> getRow(int rowIndex) { //可以用数学公式计算 List<Integer> cur = new ArrayList<>(); List<Integer> pre = new ArrayList<>(); pre.add(1); if(rowIndex == 0) return pre; for(int i=1;i<=rowIndex;i++){ cur.clear(); cur.add(1); for(int j=1;j<pre.size();j++){ cur.add(pre.get(j) + pre.get(j-1)); } cur.add(1); //pre.clear(); //System.out.println(cur.size()); pre.clear(); pre.addAll(cur); } return pre; }
还有一种解法:只需要一个数组
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if(rowIndex <0){
return list;
}
for(int i=0;i<rowIndex+1;i++){
//首位的1
list.add(0,1);
for(int j=1;j<list.size()-1;j++){
list.set(j, list.get(j)+list.get(j+1));
}
//末尾的1就不动它
}
return list;
}
相关文章推荐
- 119. Pascal's Triangle II Python
- Leetcode 119. Pascal's Triangle II
- LeetCode力扣之119. Pascal's Triangle II
- 119. Pascal's Triangle II
- [Leetcode]#119 Pascal's Triangle II
- Leetcode Pascal's Triangle II
- leetcode:pascal's_triangle_II
- 119. Pascal's Triangle II
- 119. Pascal's Triangle II
- LeetCode 119: Pascal's Triangle II
- 帕斯卡三角形—Pascal's Triangle II
- LeetCode WIith JS || 119. Pascal's Triangle II
- Pascal's Triangle II
- LeetCode 119. Pascal's Triangle II
- [leetcode, python] Pascal's Triangle II 杨辉三角
- LeetCode 119 Pascal's Triangle II
- LeetCode | Pascal's Triangle II
- LeetCode 118, 119. Pascal's Triangle i, ii
- 【leetcode】119. Pascal's Triangle II
- [LeetCode]119 Pascal's Triangle II