动态规划_leetcode62

Posted AceKo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划_leetcode62相关的知识,希望对你有一定的参考价值。

#coding=utf-8

# 递归


# 深度优先遍历,找全路径 20190306 找工作期间
class Solution1(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""

if m == 0 and n == 0:
return

self.m = m
self.n = n
self.res = 0

self.direction = [[0,1],[1,0]]

self.visit = [[False for i in range(n)] for i in range(m)]

self.findPath(0,0)

print self.res

return self.res


def inArea(self,x,y):
return x >= 0 and x < self.m and y >= 0 and y < self.n

def findPath(self,x,y):

if x == self.m-1 and y == self.n-1:
self.res += 1
return



self.visit[x][y] = True

for item in self.direction:
newX = x + item[0]
newY = y + item[1]

if self.inArea(newX,newY) and not self.visit[newX][newY]:
self.findPath(newX,newY)

self.visit[x][y] = False




# s = Solution1()
#
# s.uniquePaths(23,12)



# 记忆化递归
class Solution2(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""

if m == 0 and n == 0:
return

self.m = m
self.n = n

self.res = 0

# memo[x][y] 矩阵的方案数
# 矩阵坐标[x][y] 到 矩阵[1][1]的 路径数
self.memo = [[-1 for i in range(n+1)] for i in range(m+1)]

for i in range(n+1):
self.memo[0][i] = 0

for i in range(m+1):
self.memo[i][0] = 0

self.memo[1][1] = 1

#self.visit = [[False for i in range(n)] for i in range(m)]

return self.findPath(m, n)

def findPath(self, x, y):

if x == 1 and y == 1:
return 1

if x == 0 or y == 0: return 0 # # self.memo[x][y] = self.memo[x-1][y] + self.memo[x][y-1] if self.memo[x][y] == -1: if self.memo[x-1][y] != -1: self.memo[x][y] = self.memo[x-1][y] elif self.memo[x-1][y] == -1: self.memo[x-1][y] = self.findPath(x-1,y) self.memo[x][y] = self.memo[x - 1][y] if self.memo[x][y-1] != -1: self.memo[x][y] += self.memo[x][y-1] elif self.memo[x][y-1] == -1: self.memo[x][y-1] = self.findPath(x,y-1) self.memo[x][y] += self.memo[x][y-1] return self.memo[x][y]# s = Solution2()## print s.uniquePaths(23,12)# 动态规划class Solution3(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m == 0 and n == 0: return return self.findPath(m, n) def findPath(self, m, n): # memo[x][y] 矩阵的方案数 memo = [[-1 for i in range(n + 1)] for i in range(m + 1)] for i in range(n + 1): memo[0][i] = 0 for i in range(m + 1): memo[i][0] = 0 memo[1][1] = 1 for i in range(1,m+1): for j in range(1,n+1): if i == 1 and j == 1: continue memo[i][j] = memo[i-1][j] +memo[i][j-1] return memo[m][n]s = Solution3()print s.uniquePaths(7,3)

以上是关于动态规划_leetcode62的主要内容,如果未能解决你的问题,请参考以下文章

算法动态规划 ③ ( LeetCode 62.不同路径 | 问题分析 | 自顶向下的动态规划 | 自底向上的动态规划 )

62. 不同路径 -LeetCode

Leetcode-不同路径I和II(计数型动态规划)

Leetcode-不同路径I和II(计数型动态规划)

Leetcode-不同路径I和II(计数型动态规划)

LeetCode 62,从动态规划想到更好的解法