Combination Sum (Java)

本文详细介绍了如何使用递归方法解决在一组候选数中找到所有可能的组合,使得这些组合的元素之和等于特定目标数的问题。通过排序、回溯和剪枝等策略,有效地避免了重复解的产生,确保了解答的唯一性和效率。

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

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 C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

注意,但凡不出现重复[2,2,3] [3,2,2]这种情况,都要设一个i的start传入递归。 这道题的解决方法和题目subset以及combinations类似。

Source

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> st = new ArrayList<List<Integer>>();
        List<Integer> a = new ArrayList<Integer>();
    	if(candidates.length == 0) return st;
    	int sum = 0;
    	int start = 0;
    	
    	Arrays.sort(candidates);  //这道题的测试数据有乱序的
    	dfs(start, sum, candidates, target, st, a);
    	return st;
    }
    public void dfs(int start, int sum, int[] candidates, int target, List<List<Integer>> st, List<Integer> a){
    	if(sum > target) return;
    	if(sum == target){
    		st.add(new ArrayList<Integer>(a));
    		return;
    	}
    	
    	for(int i = start; i < candidates.length; i++){
    		a.add(candidates[i]);
    		dfs(i, sum + candidates[i], candidates, target, st, a); //注意sum是要随着dfs变化的
    		a.remove(a.size() - 1);
    	}
    }
}


Test

    public static void main(String[] args){
    	int[] candidates = {2,3,6,7};
    	int target = 7;
    	System.out.println(new Solution().combinationSum(candidates, target));
    
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值