1. 程式人生 > >[Leetcode]-Pascal's Triangle

[Leetcode]-Pascal's Triangle

reg data- fadein asc hid 生成 num %d 帕斯卡三角形

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
——-[1],
——[1,1],
—-[1,2,1],
—[1,3,3,1],
–[1,4,6,4,1]
]

題目:依據numRows生成帕斯卡三角形。帕斯卡三角形原理點擊這裏
思路:帕斯卡三角形的每行首、位元素都為1。其它的元素為上一行兩個元素之和:

if(0 == j || i == j)   r[i][j] = 1;
else                   r[i
][j] = r[i-1][j-1] + r[i-1][j];

註意事項:
1、numRows為0的時候返回0
2、一定要自己分配內存空間

#include <stdlib.h>
#include <stdio.h>

/**
 * Return an array of arrays of size *returnSize.
 * 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, int* returnSize) { if(0 == numRows) return 0; *returnSize = numRows ; int i = 0, j = 0; int** r = (int**)malloc(sizeof(int*) * numRows); //int*cn = (int*)malloc(sizeof(int) * numRows); *columnSizes = (int*)malloc(sizeof(int
) * numRows); //*columnSizes = cn; for(i=0;i<numRows;i++) { //cn[i] = i + 1; columnSizes[0][i] = i + 1 ; r[i] = (int*)malloc(sizeof(int)*(i+1)); } for(i=0;i<numRows;i++) { for(j=0;j<i+1;j++) { if(0 == j || i == j) r[i][j] = 1; else r[i][j] = r[i-1][j-1] + r[i-1][j]; } } return r; } int main() { int num = 3 ; int *columnSizes ;//每一行有幾個元素 int returnSize = 0; int **r = generate(num,&columnSizes,&returnSize); int i = 0; int j = 0; printf("toal element size is : %d\n",returnSize); for(i=0;i<num;i++) { printf("%d row have %d element \n",i,columnSizes[i]); } for(i=0;i<num;i++) { for(j=0;j<i+1;j++) printf("r[%d][%d] = %d\n",i,j,r[i][j]); printf("\n"); } }

[Leetcode]-Pascal&#39;s Triangle