首页 > 其他 > 详细

LeetCode Pascal's Triangle II

时间:2015-05-29 12:06:06      阅读:243      评论:0      收藏:0      [点我收藏+]

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;
    }
}



LeetCode Pascal's Triangle II

原文:http://blog.csdn.net/u011345136/article/details/46225961

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!