Combination Sum

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

你可能感兴趣的:(leetcode算法学习,深度优先,算法)