Leetcode 40. Combination Sum II

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
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值