标签:记忆化 col square 递归 return turn 规划 print utf-8
#coding=utf-8
# 递归版
class Solution1(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
return self.squareNum(n)
def squareNum(self,n):
if n == 0:
return 0
if n == 1:
return 1
res = n
for i in range(1,n):
if n - i ** 2 >= 0:
res = min(res, 1 + self.squareNum(n- i ** 2))
return res
# s = Solution1()
#
# print s.numSquares(13)
# 记忆化递归
class Solution2(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
self.memo = [-1 for i in range(n+1)]
return self.squareNum(n)
def squareNum(self,n):
if n == 0:
self.memo[0] = 0
return 0
if n == 1:
self.memo[1] = 1
return 1
res = n
for i in range(1,n):
if n - i ** 2 >= 0:
if self.memo[n- i ** 2] != -1:
res = min(res, 1 + self.memo[n- i ** 2])
else:
self.memo[n - i ** 2] = self.squareNum(n - i ** 2)
res = min(res, 1 + self.memo[n- i ** 2])
return res
# s = Solution2()
#
# print s.numSquares(40)
# 动归
class Solution3(object):
def numSquares(self, n):
return self.squareNum(n)
def squareNum(self, n):
self.memo = [n for i in range(n + 1)]
self.memo[0] = 0
self.memo[1] = 1
# #memo[2]
# for i in range(1, 2):
# if n - i ** 2 >= 0:
# self.memo[2] = min(self.memo[2],1+self.memo[n - i ** 2])
#
#
# #memo[3]
# for i in range(1, 3):
# if n - i ** 2 >= 0:
# self.memo[3] = min(self.memo[3],1+self.memo[n - i ** 2])
for i in range(1,n+1):
for j in range(1,i):
if i - j ** 2 >= 0:
self.memo[i] = min(self.memo[i], 1 + self.memo[i - j ** 2])
return self.memo[n]
s = Solution3()
print s.numSquares(7691)
标签:记忆化 col square 递归 return turn 规划 print utf-8
原文地址:https://www.cnblogs.com/lux-ace/p/10546548.html