1. 程式人生 > 其它 >LeetCode:118. Pascal‘s Triangle楊輝三角(C語言)

LeetCode:118. Pascal‘s Triangle楊輝三角(C語言)

技術標籤:LeetCode

題目描述:
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:
在這裡插入圖片描述

輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/pascals-triangle
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
解答:

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generate(int numRows, int* returnSize, int** returnColumnSizes) { int** ret = malloc(sizeof(int*) * numRows); *returnSize = numRows; *returnColumnSizes = malloc(sizeof(int) * numRows); for (int i = 0; i < numRows; ++i) { ret[i] = malloc(sizeof(int) * (i + 1)); (
*returnColumnSizes)[i] = i + 1; ret[i][0] = ret[i][i] = 1; for (int j = 1; j < i; ++j) { ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1]; } } return ret; }

執行結果:
在這裡插入圖片描述
Notes:
參考官方解答。