您的位置:首页 > 其它

LeetCode - Pascal's Triangle I && II

2015-03-15 23:55 381 查看
https://leetcode.com/problems/pascals-triangle/

Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,

Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]


Hide Tags
Array

这道题就是一行一行地算就行了,除了前两行以外,其余每行的中间元素都是 current[i] = prev[i-1]+prev[i],首尾元素是1.

代码如下:

public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> rst = new LinkedList<List<Integer>>();
if(numRows<=0) return rst;
for(int i=1; i<=numRows; i++){
rst.add(getrow(i, rst));
}
return rst;
}

public List<Integer> getrow(int n, List<List<Integer>> triangle){
List<Integer> rst = new LinkedList<Integer>();
rst.add(1);
if(n==1){
return rst;
}
List<Integer> prev = triangle.get(n-2);
for(int i=1; i<(n-1); i++){
rst.add(prev.get(i-1)+prev.get(i));
}
rst.add(1);
return rst;
}
}


https://leetcode.com/problems/pascals-triangle-ii/

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?

第二个跟第一个很类似,但只返回其中一排,另外空间复杂度要是O(k)

其实也是一样一排一排算,只是不把每一排都存起来,而是在数组上直接更新下一排的值。

注意:在更新下一排的值时,由于cur[j]=prev[j-1]+prev[j],所以不能从小往大算,而是应该从大往小算,这样在更新位置j时,位置j-1的值才仍然是上一排的值。

其实这个解法extra space 是O(1),因为只分配了需要被返回的List,没有再分配别的空间了。O(n)的解法应该是有两个List,一个当前的,一个前一个的。

代码如下:

public List<Integer> getRow(int rowIndex) {
List<Integer> rst = new LinkedList<Integer>();
if(rowIndex<0) return rst;
rst.add(1);
if(rowIndex==0) return rst;
for(int i=2; i<=(rowIndex+1); i++){
for(int j=(i-2); j>=1; j--){
int tmp = rst.get(j-1)+rst.get(j);
rst.set(j, tmp);
}
rst.add(1);
}
return rst;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: