Problem
Get all the combination of the number whose sum is the given value. Each number can be selected only once.
Algorithm
DFS and use tire to delete the same combination.
Code
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
# trie define
class Trie:
def __init__(self):
self.root = {}
self.buff = []
def insert(self, word):
cNode = self.root
for c in word:
if not c in cNode:
cNode[c] = {}
cNode = cNode[c]
if not 'leaf' in cNode:
cNode['leaf'] = True
def search(self, cNode, id):
# print(cNode)
str = ' ' * id * 2
for k in cNode:
# print(str, '<', k, '>')
if k == 'leaf':
ans.append(self.buff.copy())
# print(str, 'ans:', ans)
else:
self.buff.append(k)
# print(str, '->', cNode[k])
self.search(cNode[k], id+1)
self.buff.pop()
# data
trie = Trie()
buf = []
def dfs(i, n, add, tar):
if add == tar:
trie.insert(buf)
return
if i >= n:
return
if add + candidates[i] <= tar:
buf.append(candidates[i])
dfs(i+1, n, add+candidates[i], tar)
buf.pop()
dfs(i+1, n, add, tar)
candidates.sort()
dfs(0, len(candidates), 0, target)
trie.search(trie.root, 0)
return ans