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?

1st iteration:

This is like level iteration of a tree 

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        // invalid input
        if (rowIndex < 0) {
            return vector<int>(-1,1);
        }
        
        // degenerate case
        if (rowIndex == 0) {
            return vector<int>(1,1);
        }
        
        // put extra 0s at beining and end to facilitate caculation
        int zeroRow[] = {0,1,0};
        vector<int> row(zeroRow, zeroRow + sizeof(zeroRow)/sizeof(int));
        int k = 1;
        int size = row.size();
        
        // we use only one vector in the loop
        while (k <= rowIndex) {
            // add extra 0 at begining for this row
            row.push_back(0);
            
            // caculate elements of row based on previous row
            for (int i = 0; i < size-1; i++) {
                row.push_back(row[i]+row[i+1]);
            }
            
            // only keep this row by taking out previous row
            row.erase(row.begin(), row.begin()+size);
            
            // add tail zero
            row.push_back(0);
            
            // update size and k
            size = row.size();
            k++;
        }
        
        // remove extra 0s
        return vector<int>(row.begin()+1, row.end()-1);
    }
};

2nd iteration, using DP

// Justify input by left-hand
// define T[i][j] as the left-hand justified triangle
// dp transition function is:
// T[i][j] = T[i-1][j-1]+T[i][j-1] if i>0 && j>0
//         = 0 if i == 0;
//         = 0 if j == 0 execpt 1 if i == 1 && j = 0

// we only need 1D vector to caculate iteratively, as we only need previous row's info.
// we caculate from right-to-left, to avoid overwrite previous row's info.

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        assert(rowIndex >=0);
        
        // basic case
        vector<int> result;
        result.resize(rowIndex+2);
        result.assign(result.size(), 0);
        result[1] = 1;
        
        for (int i = 0; i< rowIndex; i++) {
            
            // right-to-left to avoid duplicate add due to overwrite previous row's info.
            for (int j = rowIndex+1; j>0; j--) {
                result[j] += result[j-1];
            }
        }
        
       // take out zero from head
       result.erase(result.begin());
       
       return result;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值