首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

leetcode:Pascal's Triangle II (杨辉三角,空间限制)【面试算法题】

2013-10-16 
leetcode:Pascals Triangle II (杨辉三角形,空间限制)【面试算法题】题目:Given an index k, return the kth

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


热点排行