--- title: 'LeetCode 118. Pascals Triangle' disqus: hackmd --- # LeetCode 118. Pascal's Triangle ## Description Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: ![](https://i.imgur.com/9rTqxfy.png) ## Example Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] ## Constraints 1 <= numRows <= 30 ## Answer 此題主要是考雙重指標的操作,雙重指標相當於二維矩陣,頭尾先給值,外層for跑行,內層for跑列,第2列開始要計算,抓前一行的該列和前一列做疊加。 ```Cin= //2021_11_21 int** generate(int numRows, int* returnSize, int** returnColumnSizes) { int **ans = (int**)malloc(sizeof(int*)*numRows); *returnColumnSizes = (int*)malloc(sizeof(int)*numRows); *returnSize = 0; for(int i = 0; i < numRows; i++){ (*returnColumnSizes)[*returnSize] = i + 1; ans[*returnSize] = (int*)malloc(sizeof(int)*(i + 1)); ans[*returnSize][0] = 1; ans[*returnSize][i] = 1; if(i > 1){ for(int j = 1; j < i; j++){ ans[*returnSize][j] = ans[*returnSize - 1][j - 1] + ans[*returnSize - 1][j]; } } (*returnSize)++; } return ans; } ``` ## Link https://leetcode.com/problems/pascals-triangle/ ###### tags: `Leetcode`