118. 杨辉三角 &119. 杨辉三角 II
118.
给定一个非负整数 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
class Solution: def generate(self, numRows: int) -> List[List[int]]: res=[] if numRows==0: return [] for numRow in range(numRows): row=[None for _ in range(numRow+1)] row[0]=row[-1]=1#每行首尾都是1 for i in range(1,len(row)-1): row[i]=res[numRow-1][i-1]+res[numRow-1][i] res.append(row) return res
119.
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle-ii
一开始无脑用118的代码,感觉效率不佳,

class Solution: def getRow(self, numRows: int) -> List[int]: numRows+=1 res=[] if numRows==0: return [] for numRow in range(numRows): row=[None for _ in range(numRow+1)] row[0]=row[-1]=1 for j in range(1,len(row)-1): row[j]=res[numRow-1][j-1]+res[numRow-1][j] res.append(row) return res[-1]
改了一下
class Solution: def getRow(self, rowIndex: int) -> List[int]: rowIndex+=1 res=[] for numRow in range(rowIndex): row=[None for _ in range(numRow+1)] row[0]=row[-1]=1 for j in range(1,len(row)-1): row[j]=res[numRow-1][j-1]+res[numRow-1][j] if numRow==rowIndex-1: return row res.append(row)


提交两次截然不同😅
看了一下用时20ms的也就是前面加了rowIndex==0和1的特判,其他都差不多,不管了,继续摸,,
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
新年每日一题,更新更好的解法
class Solution { public: vector<int> getRow(int rowIndex) { long cur=1; vector<int>res; for(int i=0;i<=rowIndex;i++){ res.push_back(cur); cur=cur*(rowIndex-i)/(i+1); } return res; } };


浙公网安备 33010602011771号