[NeetCode 150] Combination Target Sum

Combination Target Sum

You are given an array of distinct integers nums and a target integer target. Your task is to return a list of all unique combinations of nums where the chosen numbers sum to target.

The same number may be chosen from nums an unlimited number of times. Two combinations are the same if the frequency of each of the chosen numbers is the same, otherwise they are different.

You may return the combinations in any order and the order of the numbers in each combination can be in any order.

Example 1:

Input: 
nums = [2,5,6,9] 
target = 9

Output: [[2,2,5],[9]]

Explanation:
2 + 2 + 5 = 9. We use 2 twice, and 5 once.
9 = 9. We use 9 once.

Example 2:

Input: 
nums = [3,4,5]
target = 16

Output: [[3,3,3,3,4],[3,3,5,5],[4,4,4,4],[3,4,4,5]]

Example 3:

Input: 
nums = [3]
target = 5

Output: []

Constraints:

All elements of nums are distinct.

1 <= nums.length <= 20
2 <= nums[i] <= 30
2 <= target <= 30

Solution

To search for the combinations without repetition, we can try each number in nums in an ascending order. In DFS, we will try to put small number first and then try larger numbers after recursion. A list is passed as a parameter of DFS to memorize the numbers we put before and will be stored as one of the answers if we meet the target.

Code

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

        def dfs(i, comb, summ):
            if summ > target or i >= len(nums):
                return
            if summ == target:
                ans.append(comb[:])
                return
            comb.append(nums[i])
            dfs(i, comb, summ+nums[i])
            comb.pop()
            dfs(i+1, comb, summ)
        
        dfs(0, [], 0)
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值