Skip to content

Commit 82d2c40

Browse files
committed
指定k个整数组合(dfs+回溯)
1 parent cc226a4 commit 82d2c40

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Backtracking/216_CombinationSumIII.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/combination-sum-iii/description.
6+
题目描述:
7+
8+
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be
9+
used and each combination should be a unique set of numbers.
10+
11+
12+
Example 1:
13+
14+
Input: k = 3, n = 7
15+
16+
Output:
17+
18+
[[1,2,4]]
19+
20+
Example 2:
21+
22+
Input: k = 3, n = 9
23+
24+
Output:
25+
26+
[[1,2,6], [1,3,5], [2,3,4]]
27+
Credits:
28+
Special thanks to @mithmatt for adding this problem and creating all test cases.
29+
30+
"""
31+
32+
33+
class Solution(object):
34+
def combinationSum3(self, k, n):
35+
"""
36+
:type k: int
37+
:type n: int
38+
:rtype: List[List[int]]
39+
"""
40+
if n < k:
41+
return []
42+
43+
ans = []
44+
sub = []
45+
self.backtrace(k, n, 1, sub, ans)
46+
47+
return ans
48+
49+
def backtrace(self, k, n, idx, sub, ans):
50+
if n < 0 or len(sub) > k:
51+
return
52+
elif n == 0 and len(sub) == k:
53+
ans.append(sub[:])
54+
else:
55+
for i in range(idx, 10):
56+
sub.append(i)
57+
self.backtrace(k, n - i, i + 1, sub, ans)
58+
sub.pop()

0 commit comments

Comments
 (0)