LeetCode 118. 楊輝三角(C、C++、python)
阿新 • • 發佈:2018-12-13
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5 輸出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
C
/** * Return an array of arrays. * 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** res=(int**)malloc(sizeof(int*)*numRows); *columnSizes=(int*)malloc(sizeof(int)*numRows); for(int i=0;i<numRows;i++) { res[i]=(int*)malloc(sizeof(int)*(i+1)); res[i][0]=1; res[i][i]=1; for(int j=1;j<i;j++) { res[i][j]=res[i-1][j]+res[i-1][j-1]; } (*columnSizes)[i]=i+1; } return res; }
C++
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> res(numRows); for(int i=0;i<numRows;i++) { res[i]=vector<int>(i+1,1); } if(numRows>2) { for(int i=2;i<numRows;i++) { for(int j=1;j<i;j++) { res[i][j]=res[i-1][j]+res[i-1][j-1]; } } } return res; } };
python
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ res=[] for i in range(0,numRows): res.append([1]) for j in range(1,i+1): if j==i: res[i].append(1) else: res[i].append(res[i-1][j]+res[i-1][j-1]) return res;