您的位置:首页 > 其它

LeetCode Pascal's Triangle II

2015-05-29 10:14 204 查看
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)的空间。
思路:这次利用递推,每行的结果都是基于上一行的,然后再从每行的后面开始递推,就不会有影响了。

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