LeetCode 119. Pascal's Triangle II

来源:互联网 发布:it设备维修流程图 编辑:程序博客网 时间:2024/06/15 13:07

一道递归问题,最初程序如下,可运行时报错为指针指向未知位置:


class Solution {

public:

    vector<int> getRow(int rowIndex) {
        
       
       vector<int> Row;
        
        for(int i=0; i<rowIndex+1; i++)
        {
            for(int j=i; j>=1; j--)
            {
                Row[j] += Row[j-1];
            }
            Row[0] = 1;
        }
        return Row;
       
    }

};


后来找到错误行为Row[0] = 1, 因为最初定义Row时未指定Row的大小,所以编译无法通过。


解决办法:1. 定义Row时指定数组大小

  2. 采用push_back将元素1入栈


1.

class Solution {

public:

    vector<int> getRow(int rowIndex) {
        
       
       vector<int> Row[rowIndex+1, 0];
        
        for(int i=0; i<rowIndex+1; i++)
        {
            for(int j=i; j>=1; j--)
            {
                Row[j] += Row[j-1];
            }
            Row[0] = 1;
        }
        return Row;
       
    }

};



2.

class Solution {

public:
    vector<int> getRow(int rowIndex) {
        
       
       vector<int> Row;
        
        for(int i=0; i<rowIndex+1; i++)
        {
            for(int j=i; j>=1; j--)
            {
                Row[j] += Row[j-1];
            }
            Row.push_back(1);
        }
        return Row;
       
    }
};
原创粉丝点击