-
Notifications
You must be signed in to change notification settings - Fork 0
/
integer-break.py
49 lines (41 loc) · 1.04 KB
/
integer-break.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0]*(n+1)
dp[0],dp[1] = 0,0
res = 0
for i in xrange(2,n+1):
cur = 0
for j in xrange(1,i):
cur = max(cur, j*(i-j), j*dp[i-j])
dp[i] = cur
print dp
return dp[-1]
# DFS实现
def integerBreak(self, n):
def dfs(n):
if n<=2:
return 1
res = 0
for i in xrange(1,n):
res = max( res, i*(n-i), i*dfs(n-i) )
return res
return dfs(n)
# DFS+记忆化
def integerBreak(self, n):
d = dict()
def dfs(n):
if n in d:
return d[n]
if n<=2:
d[2] = 1
return 1
res = 0
for i in xrange(1,n):
res = max( res, i*(n-i), i*dfs(n-i) )
d[n] = res
return res
return dfs(n)