Combination Sum

本文介绍了一个编程问题,要求从给定的不重复整数数组中找出所有和为目标值的独特组合。使用深度优先搜索算法进行遍历,同时讨论了时间复杂度(指数级)和空间复杂度(O(n))。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the 

frequency

 of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

Input: candidates = [2], target = 1
Output: []

Intuition

The task is to find all possible combinations of elements from an array candidates such that their sum is equal to a given target. The solution involves using a depth-first search (DFS) approach to explore all possible combinations.

Approach

Initialize Result List:

Create an empty list res to store the resulting combinations.
DFS Function:

Implement a DFS function (dfs) that takes three arguments: the current index i, the current combination cur, and the current sum total.
The base case is when total is equal to the target. In this case, add a copy of the current combination cur to the result res.
In the recursive case:
Include the element at index i in the current combination cur.
Call the DFS function with the same index i, the updated combination cur, and the updated sum total + candidates[i].
Remove the last element from the current combination to backtrack.
Call the DFS function with the next index i + 1, the current combination cur, and the unchanged sum total.
Main Function:

Call the DFS function with an initial index of 0, an empty combination, and an initial sum of 0.
Return Result:

Return the final result res.

Complexity

  • Time complexity:

The time complexity is determined by the number of recursive calls and is exponential in the worst case. It is influenced by the branching factor and the depth of the recursion.

  • Space complexity:

The space complexity is O(n) due to the recursion stack. Additionally, the space required for the cur list contributes to the space complexity. The result res contains the combinations, each with an average length of n/2, resulting in a space complexity of O(n * 2^n).

Code

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []

        def dfs(i, cur, total):
            if total == target:
                res.append(cur.copy())
                return
            elif i >= len(candidates) or total > target:
                return

            cur.append(candidates[i])
            dfs(i, cur, total + candidates[i])
            cur.pop()
            dfs(i + 1, cur, total)

        dfs(0, [], 0)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值