leetcode:Pascal's Triangle II

来源:互联网 发布:网络带给我们的坏处 编辑:程序博客网 时间:2024/06/05 04:26

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,

     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]

Return [1,3,3,1].

Note:

Could you optimize your algorithm to use only O(k) extra space?

注意从后往前遍历 f(i,j)=f(i-1,j-1)+f(i-1,j) ,【这一行这一列】等于【上一行这一列与前一列之和】

f(i,j)存放在f(i-1,j)的位置,就是列的位置不变

     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]

class Solution {public:    vector<int> getRow(int rowIndex) {       vector<int> array;        for (int i = 0; i <= rowIndex; i++)       {            //从后往前加           for (int j = i - 1; j > 0; j--)           {                array[j] = array[j - 1] + array[j];            }            array.push_back(1);       }        return array;    }};
http://www.cnblogs.com/felixfang/p/3865135.html

0 0
原创粉丝点击