标签:length art return 排列 pen range [] 要求 numpy
这个问题卡了两天,自己也想到了可行的方法,但还是因为时间超出了限制。这个问题的关键在于动态规划,存储中间计算值,这样就大大节约了计算时间。
自己从全排列想到的方法,向右为0,向下为0,先排序出所有的走法,后for循环计算,最后求所有走法中的最小值。
class Solution(object):
def minPathSum(self, grid):
"""
最小路径
:type grid: List[List[int]]
:rtype: int
"""
w = len(grid[0])
h = len(grid)
l = [0]*(w-1)+[1]*(h-1)
l = self.permuteUnique(l)
# print(l)
if l:
lSum = []
for i in l:
s = grid[0][0]
a = 0
b = 0
for j in i:
if j==0:
a += 1
s += grid[b][a]
else:
b += 1
s += grid[b][a]
lSum.append(s)
# print(lSum)
return min(lSum)
else:
return grid[0][0]
def permuteUnique(self, nums):
"""
全排列2优化
:type nums: List[int]
:rtype: List[List[int]]
"""
self.result = []
self.permutation(nums,0)
# print(self.result)
return self.result
def permutation(self,nums,start):
length = len(nums)
if start == length-1:
# print(nums)
n = nums[:]
self.result.append(n)
temp = []
for i in range(start,length):
if nums[i] not in temp:
temp.append(nums[i])
nums = self.swap(nums,start,i)
self.permutation(nums,start+1)
nums = self.swap(nums,start,i)
def swap(self,l,start,end):
l[start],l[end] = l[end],l[start]
return l
但是显然上述的方法时间复杂度为O(n*m),不符合要求。
正解:
import numpy as np
class Solution(object):
def minPathSum(self, grid):
"""
最小路径
:type grid: List[List[int]]
:rtype: int
"""
grid = np.array(grid,dtype=np.int64)
w = grid.shape[1]
h = grid.shape[0]
temp = grid.copy()
# print(temp)
for i in range(h):
if i!=0:
temp[i,0] += temp[i-1,0]
for j in range(w):
if j!=0:
temp[0,j] += temp[0,j-1]
for i in range(1,h):
for j in range(1,w):
temp[i,j] = self.min(temp[i-1,j],temp[i,j-1])+temp[i,j]
# print(temp)
return temp[h-1,w-1]
def min(self,a,b):
if a<b:
return a
else:
return b
标签:length art return 排列 pen range [] 要求 numpy
原文地址:https://www.cnblogs.com/zenan/p/9501093.html