Array Pascal's Triangle II

来源:互联网 发布:网络通讯设备 编辑:程序博客网 时间:2024/06/08 09:21

思路:

类似I的思路,算完上一层才能算下一层,加入了滚动数组的思想。每一层从中间开始计算,计算好中间到开始的所有元素,中间到结尾的元素与其对称。

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> row;        row.push_back(1);        if(rowIndex == 0) return row;        row.push_back(1);        if(rowIndex == 1) return row;        // >= 2        for(int i = 2; i <= rowIndex; ++i) {            row.resize(i+1);            for(int j = i/2; j >= 1; --j) {                row[j] = row[j-1] + row[j];            }            //copy front2mid to the mid2end            int size = (i%2 == 0) ? i/2-1 : i/2;            for(int j = 0; j <= size; ++j) {                row[i-j] =row[j];            }        }        return row;    }};
0 0