Combination Sum

本文介绍了一种寻找候选数集合中所有可能组合的算法,这些组合的和等于目标数。该算法允许重复使用集合中的元素,并通过递归深度优先搜索实现。文章提供了Java和Python两种语言的实现代码。

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from Cunlimited number of times.

java

public class Solution {
    /*
     * @param candidates: A list of integers
     * @param target: An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        int[] candidate = removeDuplicate(candidates);
        dfs(candidate, target, 0, new ArrayList<Integer>(), result);
        return result;
    }
    private int[] removeDuplicate(int[] candidates) {
        Arrays.sort(candidates);
        int index = 0;
        for (int i = 0; i < candidates.length; i++) {
            if (candidates[index] != candidates[i]) {
                candidates[++index] = candidates[i];
            }
        }
        int[] arr = new int[index + 1];
        for (int i = 0; i < index + 1; i++) {
            arr[i] = candidates[i];
        }
        return arr;
    }
    private void dfs(int[] candidates, 
                     int target,
                     int startIndex,
                     List<Integer> list, 
                     List<List<Integer>> result) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            list.add(candidates[i]);
            dfs(candidates, target - candidates[i], i, list, result);
            list.remove(list.size() - 1);
        }
    }
}
python

class Solution:
    """
    @param: candidates: A list of integers
    @param: target: An integer
    @return: A list of lists of integers
    """
    def combinationSum(self, candidates, target):
        # write your code here
        if candidates is None or len(candidates) == 0:
            return []
        candidates = self.removeDuplicate(candidates)
        result = []
        self.dfs(candidates, target, 0, [], result)
        return result
    
    def removeDuplicate(self, candidates):
        candidates.sort()
        index = 0
        for i in range(len(candidates)):
            if candidates[index] != candidates[i]:
                index += 1
                candidates[index] = candidates[i]
        return candidates[: index + 1]

    def dfs(self, candidates, target, startIndex, arr, result):
        if target < 0:
            return 
        if target == 0:
            result.append(list(arr))
        for i in range(startIndex, len(candidates)):
            arr.append(candidates[i])
            self.dfs(candidates, target - candidates[i], i, arr, result)
            arr.pop()
        



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ncst

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

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

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

打赏作者

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

抵扣说明:

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

余额充值