码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[119]-Pascal's Triangle II

时间:2015-06-09 13:51:09      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:index   triangle   设置   return   

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?


分析:通过递归设置vector的值,变量i表示当前行数,同时根据行数可以得到当前的vector元素个数。如果我们从前往后遍历,当i增加的时候,我们的num[j] = num[j] + num[j-1]就会出问题,因为num[j+1]=num[j+1]+num[j],而num[j]已经更新了。

所以这里采用的是从后往前遍历,num[j] = num[j] + num[j-1],这样num[j-1] = num[j-1] + num[j-2],不会受到前面的num[j]的变化而变化。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> nums(rowIndex+1);
        for(int i = 0; i <= rowIndex; i++){
            nums[i] =1;
            for(int j = i-1; j >= 1; j--){
                nums[j] = nums[j] + nums[j-1];
            }
        }
        return nums;
    }
};

Leetcode[119]-Pascal's Triangle II

标签:index   triangle   设置   return   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46425431

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!