LeetCode(119)Pascal's Triangle II

来源:互联网 发布:mysql函数与存储过程 编辑:程序博客网 时间:2024/05/09 23:45

题目如下:

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行的Pascal's Triangle.

我的代码:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res;        if(rowIndex<0)            return res;        res.push_back(1);        for(int i=1;i<rowIndex+1;i++){            int pre=0;            int pre_size=(int)res.size();            for(int j=0;j<pre_size;j++){                int cur=res[j];                res[j]=pre+res[j];                pre=cur;            }            res.push_back(1);        }        return res;    }};


update:  简单的一维动态规划

03-08-2015

// 2ms class Solution {public:    vector<int> getRow(int rowIndex) { //看清楚题,k从0开始计数,不是从1开始计数。        vector<int> result;        if (rowIndex < 0) return result;        result.push_back(1);        for (int i = 1; i <= rowIndex; ++i) {            result.push_back(result.back());            for (int j = i - 1; j > 0; --j) {                result[j] += result[j - 1];            }        }        return result;    }};


0 0
原创粉丝点击