【566. 重塑矩阵】
- 暴力破解
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
m = len(mat)
n = len(mat[0])
if m*n != r*c:
return mat
else:
onemat = []
for i in range(m):
for j in range(n):
onemat.append(mat[i][j])
newmat = []
for i in range(r):
newmat.append([])
for i in range(r):
for j in range(c):
newmat[i].append(onemat[i*c+j])
return newmat
算法复杂度:O(n^2)
【118. 杨辉三角】
- 暴力破解
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 1:
return [[1]]
elif numRows == 2:
return [[1],[1,1]]
else:
results = [[1],[1,1]]
for i in range(2,numRows):
results.append([1])
for j in range(i-1):
newnum = results[i-1][j] + results[i-1][j+1]
results[i].append(newnum)
results[i].append(1)
return results
- 动态规划
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
dp = [[1]]
for i in range(1, numRows):
dp.append(dp[-1] + [1])
for j in range(1, len(dp[-1]) - 1):
dp[-1][j] = dp[-2][j - 1] + dp[-2][j]
return dp
# 作者:himymBen
# 链接:https://leetcode-cn.com/problems/pascals-triangle/solution/pythongo-dong-tai-gui-hua-by-himymben-v1oz/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。