forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
form-largest-integer-with-digits-that-add-up-to-target.py
71 lines (65 loc) · 1.87 KB
/
form-largest-integer-with-digits-that-add-up-to-target.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Time: O(t)
# Space: O(t)
class Solution(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
dp = [0]
for t in xrange(1, target+1):
dp.append(-1)
for i, c in enumerate(cost):
if t-c < 0 or dp[t-c] < 0:
continue
dp[t] = max(dp[t], dp[t-c]+1)
if dp[target] < 0:
return "0"
result = []
for i in reversed(xrange(9)):
while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:
target -= cost[i]
result.append(i+1)
return "".join(map(str, result))
# Time: O(t)
# Space: O(t)
class Solution2(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
def key(bag):
return sum(bag), bag
dp = [[0]*9]
for t in xrange(1, target+1):
dp.append([])
for d, c in enumerate(cost):
if t < c or not dp[t-c]:
continue
curr = dp[t-c][:]
curr[~d] += 1
if key(curr) > key(dp[t]):
dp[-1] = curr
if not dp[-1]:
return "0"
return "".join(str(9-i)*c for i, c in enumerate(dp[-1]))
# Time: O(t^2)
# Space: O(t^2)
class Solution3(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
dp = [0]
for t in xrange(1, target+1):
dp.append(-1)
for i, c in enumerate(cost):
if t-c < 0:
continue
dp[t] = max(dp[t], dp[t-c]*10 + i+1)
return str(max(dp[t], 0))