读书人

leetcode:Pascalamp;#39;s Triangle II

发布时间: 2013-10-16 11:29:46 作者: rapoo

leetcode: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?

题意输出杨辉三角形第k行,空间限制为O(k)。


循环利用当前数组,用上一行相邻两个数值和做当前值,注意改变数组值之前,用p存当前的值,因为下一次操作还要用到这个值。

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int >result;        result.push_back(1);        for(int i=1;i<=rowIndex;++i)        {            int p=1,temp;            for(int j=1;j<i;++j)            {                temp=p;                p=result[j];                result[j]=temp+result[j];            }            result.push_back(1);        }        return result;    }};// http://blog.csdn.net/havenoidea


读书人网 >其他相关

热点推荐