小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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?

分析

与上题LeetCode 118 Pascal’s Triangle本质相同;

需要注意的是,本题参数 k = 3 代表下标为3的那行元素,下标计算从0开始,也就是第4行;

AC代码

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if (rowIndex == 0)
            return  vector<int>(1,1);

        //存储上一行vector
        vector<int> pre = getRow(rowIndex - 1);

        //计算当前行
        vector<int> cur(rowIndex + 1, 0);
        //初始化首尾元素
        cur[0] = 1;
        cur[rowIndex] = 1;

        //计算中间元素
        for (int i = 1; i < rowIndex; ++i)
        {
            cur[i] = pre[i-1] + pre[i];
        }//for

        return cur;
    }
};

GitHub测试程序源码

posted on 2015-10-09 21:33  Coding菌  阅读(103)  评论(0编辑  收藏  举报