首页 > 其他 > 详细

[Leetcode]-Pascal's Triangle II

时间:2015-07-04 15:34:26      阅读:235      评论:0      收藏:0      [点我收藏+]

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?

Hide Tags : Array
题目:返回帕斯卡三角形第K行的元素,顶点1即为第0行。
注意:只能使用O(k)额外空间

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* getRow(int rowIndex, int* returnSize) {
    *returnSize = rowIndex+1;
    if(0 > rowIndex) return 0;
    int* r = (int*)malloc(sizeof(int)*(rowIndex+1));

    if(0 == rowIndex)
    {
        r[0] = 1;
        return r;
    }

    int i = 0 ,j = 0;

    int m=0,n=0;
    for(i=1;i<=rowIndex;i++)
    {
        r[0] = r[i] = 1;
        m = r[0];
        n = r[1];
        for(j=1;j<i;j++)
        {
            r[j] = m + n;
            m = n;
            n = r[j+1];
        }
    }
    return r;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[Leetcode]-Pascal's Triangle II

原文:http://blog.csdn.net/xiabodan/article/details/46755067

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!