78. Subsets
77. Combinations
class Solution:
def combine(self, n, k):
res = []
def dfs(k, tmp, start):
if k == 0:
res.append(tmp.copy())
return
for num in range(start, n + 1):
tmp.append(num)
dfs(k - 1, tmp, num + 1)
tmp.pop()
dfs(k, [], 1)
return res
227. Basic Calculator II
class Solution:
def combinationSum3(self, k, n):
res = []
def dfs(k, start, sum, tmp):
if k == 0:
if sum == 0:
res.append(tmp.copy())
return
for i in range(start, 10):
tmp.append(i)
dfs(k-1, i+1, sum-i, tmp)
tmp.pop()
dfs(k, 1, n, [])
return res
def combinationSum3_2(self, k: int, n: int) -> List[List[int]]:
res = []
def dfs(k, start, sum, tmp):
if k == 0:
if sum == 0:
res.append(tmp.copy())
return
for i in range(start, 10):
if k > 1 and sum - i <= 0 :
continue
else:
tmp.append(i)
dfs(k-1, i+1, sum-i, tmp)
tmp.pop()
dfs(k, 1, n, [])
return res
17. Letter Combinations of a Phone Number
class Solution:
def letterCombinations(self, digits):
if digits == '':
return []
dic = {'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'],
'9': ['w', 'x', 'y', 'z']}
res = []
def dfs(index, tmp):
if index == len(digits):
res.append(tmp)
return
for char in dic[digits[index]]:
tmp += char
dfs(index+1, tmp)
tmp = tmp[:-1]
dfs(0, '')
return res
39. Combination Sum
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates = sorted(candidates)
def dfs(start, target, tmp):
if target == 0:
res.append(tmp.copy())
return
for index in range(start, len(candidates)):
if target - candidates[index] < 0:
break
tmp.append(candidates[index])
dfs(index, target-candidates[index], tmp)
tmp.pop()
dfs(0, target, [])
return res
40. Combination Sum II
- 只能用一次!
- 去重trick:搜过的就不用再搜了,continue掉;ps,先sort,那么就是跟前面对比下一不一样就知道搜过没了;
if index > start and candidates[index - 1] == candidates[index]: continue
!!!重要!- 另外剪枝了
- 因为只能用一次,判断下当前到最后还够不够,一个点不够了,后面的点就都不够了;break掉;
- 和超过target;由于sort过了,所以break掉;
class Solution:
def combinationSum2(self, candidates, target):
res = []
candidates = sorted(candidates)
def dfs(start, target, tmp):
if target == 0:
if tmp not in res:
res.append(tmp.copy())
return
for index in range(start, len(candidates)):
if sum(candidates[start:]) < target:
break
if target - candidates[index] < 0:
break
if index > start and candidates[index - 1] == candidates[index]:
continue
tmp.append(candidates[index])
dfs(index+1, target-candidates[index], tmp)
tmp.pop()
dfs(0, target, [])
return res
131. Palindrome Partitioning