首页 > 其他 > 详细

Pescal Triangle Two

时间:2017-10-16 22:56:54      阅读:197      评论:0      收藏:0      [点我收藏+]

Description:

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?

 

Thoughts:
我们从前一个例子Pascal triangle的第二种方法可以得到启发;只需要去掉外面用来保存每一行List值的ArrayList即可。不过要注意的一个问题就是Pascal triangle中的rownums会比Pascal triangle two中的rowIndex多1,所以有以下的java代码:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> result = new ArrayList<Integer>();
        rowIndex++;
        for(int i=0;i<rowIndex;i++){
            result.add(0, 1);
            for(int j = 1;j<result.size()-1;j++){
                result.set(j, result.get(j)+result.get(j+1));
            }
        }
        return result;
    }
}

 

Pescal Triangle Two

原文:http://www.cnblogs.com/whatyouknow123/p/7679157.html

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