首页 > 其他 > 详细

[LeetCode] Pascal's Triangle II

时间:2015-05-12 15:42:43      阅读:283      评论:0      收藏:0      [点我收藏+]

Pascal‘s 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),我们只需记录上一层的记录即可。这里的k从0开始计数。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if(rowIndex<0){
            return vector<int>();
        }
        vector<int> result;
        result.push_back(1);
        for(int i = 1; i< rowIndex + 1; i++){       //第i行
            vector<int> lastRow = result;
            result.resize(i+1);
            for(int j=0; j<i+1; j++){           //第i行第j个数
                if(j==0||j==i){
                    result[j]=1;
                }else{
                    result[j] = lastRow[j-1]+lastRow[j];
                }
            } 
        }
        return result;
    }
};


[LeetCode] Pascal's Triangle II

原文:http://blog.csdn.net/kangrydotnet/article/details/45669281

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