forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum-iii.py
More file actions
executable file
·77 lines (65 loc) · 2.43 KB
/
combination-sum-iii.py
File metadata and controls
executable file
·77 lines (65 loc) · 2.43 KB
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
72
73
74
75
76
77
"""
If you haven't seen [this problem](https://leetcode.com/problems/combinations/), I suggest you do that first!
And here is the [explaination](https://leetcode.com/problems/combinations/discuss/387753) for that problem.
This problem is basically the same as [that problem](https://leetcode.com/problems/combinations/) with its N=9.
The difference is we have to find the combination that sum up as N.
So all we have to do is change the condition of [0]. And the condition for backtracking [1].
"""
class Solution(object):
def combinationSum3(self, K, N):
answer = []
ans = []
first = 1
total = 0
while True:
if len(ans)==K and total==N: #[0]
answer.append(ans[:])
if len(ans)==K or total>N or first>9: #[1]
if not ans: return answer
first = ans.pop() #backtrack
total-=first
first+=1
else:
ans.append(first)
total+=first
first+=1
#DFS
class Solution(object):
def combinationSum3(self, K, N):
def dfs(path, min_num):
if len(path)==K and sum(path)==N:
opt.append(path)
for num in xrange(min_num, 10):
dfs(path+[num], num+1)
opt = []
dfs([], 1)
return opt
"""
Use a helper to check the remain.
comb is the combination to sum up to remain.
k is the max length of comb.
start is the starting index of "nums", since we already explore the all the possible comb from previous index.
Time: O(9!/(9-k)! * k), 9*8*7... for k times. And each ans takes O(k) to copy the comb list.
Space: O(k)
"""
class Solution(object):
def combinationSum3(self, k, n):
def helper(remain, comb, k, start):
if remain==0 and len(comb)==k:
ans.append(comb[:])
elif remain<0 or len(comb)>k:
return
else:
for i in xrange(start, len(nums)):
used = nums[i]
num = i+1
if used: continue
comb.append(num)
nums[i] = True
helper(remain-num, comb, k, i+1)
comb.pop()
nums[i] = False
nums = [False]*9
ans = []
helper(n, [], k, 0)
return ans