【LeetCode 40】组合总和

本文介绍了一个名为 combinationSum2 的算法实现,该算法用于找出所有可能的组合,使得候选数之和等于目标值。在组合中,每个数字在每个组合中只能使用一次,并且数字集合中的数字需要按非递减顺序排列。通过深度优先搜索(DFS)遍历所有可能的组合,同时利用排序和跳过重复元素的方法避免重复解。

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

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	Arrays.sort(candidates);
    	List<Integer> ret = new ArrayList<Integer>();
    	dfs(candidates, target, ret, list, 0);
    	return list;
    }
    
    private static void dfs(int[] nums, int target, List<Integer> ret, List<List<Integer>> list, int begin)
    {
    	if (target == 0)
    	{
    		list.add(new ArrayList(ret));
    		return;
    	}
    	for (int i = begin; i < nums.length; i++)
    	{
    		while (i > begin && i < nums.length && nums[i] == nums[i-1])
    			i++;
    		if (i == nums.length || target - nums[i] < 0)
    			break;
    		ret.add(nums[i]);
    		dfs(nums, target-nums[i], ret, list, i+1); // 减去当前值,下一个计算从i+1开始,而不是从现在的i开始计算
    		ret.remove(ret.size()-1);
    	}
    	
    }