数据结构算法操作试题(C++/Python)—— 组合总和

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)—— 组合总和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/combination-sum/

2. 解答

python: 58ms, 10.8 mb

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        def dfs(remain,path):
            if not remain:
                res.append(path)
                return
            for i in candidates:
                if i>remain:
                    break
                elif path and i<path[-1]:
                    continue
                else:
                    dfs(remain-i,path+[i])
        dfs(target,[])
        return res

其他方法看 leetcode 链接 评论区~