Combination Sum II

本文详细介绍了如何使用递归深度优先搜索(DFS)算法解决候选数集合中寻找所有可能的组合,使得这些组合的和等于目标值的问题。文章提供了两种实现方式:一种使用HashSet去除重复组合,另一种直接在遍历时跳过重复元素。代码示例包括Java和Python两种语言。

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

Each number in C may only be used once in the combination.

java

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        Arrays.sort(candidates);
        Set<List<Integer>> set = new HashSet<>();
        dfs(candidates, target, 0, new ArrayList<Integer>(), set);
        return new ArrayList<List<Integer>>(set);
    }
    private void dfs(int[] candidates, 
                     int target, 
                     int startIndex, 
                     List<Integer> list, 
                     Set<List<Integer>> set) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            set.add(new ArrayList<Integer>(list));
        }
        for (int i = startIndex; i < candidates.length; i++) {
            list.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1, list, set);
            list.remove(list.size() - 1);
        }
    }
}

java

public class Solution {
    /*
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (num == null || num.length == 0) {
            return result;
        }
        Arrays.sort(num);
        dfs(num, target, 0, new ArrayList<Integer>(), result);
        return result;
    }
    private void dfs(int[] num, 
                     int target, 
                     int startIndex, 
                     List<Integer> list, 
                     List<List<Integer>> result) {
        if (target < 0) {
            return;
        }          
        if (target == 0) {
            result.add(new ArrayList<Integer>(list));
        }
        for (int i = startIndex; i < num.length; i++) {
            if (i != startIndex && num[i] == num[i - 1]) {
                continue;
            }
            list.add(num[i]);
            dfs(num, target - num[i], i + 1, list, result);
            list.remove(list.size() - 1);
        }
    }
}

python

class Solution:
    """
    @param: num: Given the candidate numbers
    @param: target: Given the target number
    @return: All the combinations that sum to target
    """
    def combinationSum2(self, num, target):
        # write your code here
        if num is None or len(num) == 0:
            return []
        result = []
        num.sort()
        self.dfs(num, target, 0, [], result)
        return result
        
    def dfs(self, num, target, startIndex, arr, result):
        if target < 0:
            return
        if target == 0:
            result.append(list(arr))
        for i in range(startIndex, len(num)):
            if i != startIndex and num[i] == num[i - 1]:
                continue
            arr.append(num[i])
            self.dfs(num, target - num[i], i + 1, 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、付费专栏及课程。

余额充值