leetcode 119. Pascal's Triangle II

来源:互联网 发布:一千个哈姆雷特 知乎 编辑:程序博客网 时间:2024/05/21 00:51

原题:

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?

输出杨辉三角的某一行的值。

代码如下:

/** * 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;    int** temp;    temp=(int**)malloc(sizeof(int*)*(rowIndex+1));    for(int n=0;n<rowIndex+1;n++)    {        *(temp+n)=(int*)malloc(sizeof(int)*(n+1));        for(int m=0;m<=n;m++)        {            if(m==0||m==n)            {                temp[n][m]=1;            }            else            {                temp[n][m]=temp[n-1][m-1]+temp[n-1][m];            }        }    }    return *(temp+rowIndex);  }

一行一行算算就好咯。

原创粉丝点击