leetcode-118-Pascal's Triangle 基础题

问题

题目:[leetcode-118]

思路

基础题,杨辉三角。

代码(c++实现)

//c++ version
class Solution {
public:
    vector<vector<int>> generate(int numRows) {

        vector< vector<int> > ret;
        for( int i = 0; i < numRows; ++i )
        {
            vector< int > t;
            if( !i )
            {
                t.push_back(1);
                ret.push_back(t);
            }
            else
            {
                for( int j = 0; j <= i; ++j )
                {
                    if( !j || j == i )
                        t.push_back(1);
                    else
                        t.push_back(ret[i-1][j-1] + ret[i-1][j]);
                }
                ret.push_back(t);
            }
        }
        return ret;
    }
};

下面用c实现,这个题思路不难。不过c的实现还花了我点时间,主要是题意的理解问题。其实指针本省的使用没问题,但是对于题目要怎么样用指针没有理解好。主要是对columnSizes的理解,*columnSizes是一个一维数组。存储每一行的大小。这没有问题,关键是这个变量本省有没有开辟空间我不知道,起初以为就是一个指针,连这个变量也没有开辟。所以,在代码中开辟了三块内存空间:

  • tri
  • columnSizes(这一块的开辟导致程序的错误)
  • *columnSizes
    按照题目的意思,第二块的开辟是没有必要的。这个从注释最后一句话应该是可以得到的。所以,对题目的理解还是要仔细。

代码1(c实现)

//c version
/**
 * Return an array of arrays.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generate(int numRows, int** columnSizes) {
    if( numRows <= 0 )
        return NULL;

    int** tri = (int**)malloc( sizeof(int*) * numRows );
    if( !tri )
        return NULL;

    *columnSizes = (int*)malloc( sizeof(int) * numRows );
    if( !(*columnSizes) )
        return NULL;

    for( int i = 0; i < numRows; ++i )
    {
        tri[i] = (int*)malloc( sizeof(int) * (i+1) );
        if(!tri[i])
            return NULL;
        *((*columnSizes)+i) = i + 1;

        for( int j = 0; j <= i; ++j )
        {
            if( !j || j == i )
                tri[i][j] = 1;
            else
                tri[i][j] = tri[i-1][j-1] + tri[i-1][j];    
        }
    }
    return tri;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值