Combination Sum

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:
1. All numbers (including target) will be positive integers.
2. 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]
]

注释:给定一个整数数组C和一个目标整数T,找出C中所有组合,使组合之和等于T。数组C中数字可以不限次数使用。
数组C中所有整数都为整数,T亦一样;结果集中不包含重复结果。

假设C是升序排列的,从C中按顺序取出整数存入tmp中,tmp中所有数字之和为sum。
1. 当sum大于T时,不符合条件;
2. 当sum等于T时,符合条件,此时tmp是一个结果集;
3. 当sum小于T时,从C中继续取出数存入tmp中
重复上述步骤,在将整数存入tmp中进行判断后,需要再将该整数从tmp中踢出(回溯法)

C:[2,3,6,7]和T:7为例进行分析:
初始化:tmp={} sum =0
取2存入tmp,tmp={2}, sum= 2;进行第三步,此时应继续从2开始取值,再次将2存入tmp, tmp= {2,2}, sum = 4 ;再重复第三步两次后,tmp={2,2,2,2} sum= 8,由于sum>T,不符合条件。
此时,需要退回到tmp={2,2,2} sum=6 的状态,重复取后面的值3,6,7;
再次退回tmp={2,2} sum = 4 的状态,取值3之后,tmp={2,2,3} sum = 7,满足sum = T,因此tmp={2,2,3}为一个解。
再以2为开头的所有组合判断完后,需要从3开始继续判断,并且不能有取值为2的组合(所有组合是唯一的

下面附上实现代码:

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();//存储所有组合
    List<Integer> tmp = new ArrayList<Integer>();//存储当前组合
    Arrays.sort(candidates);//候选数组排序
    findSum(candidates, target, 0, result, tmp, 0);

    return result;
}
public void findSum(int[] candidates, int target, int sum, List<List<Integer>> result, List<Integer> tmp, int level){
    if(sum > target) {
        return ;
    }
    if (sum == target) {
        result.add(new ArrayList<Integer>(tmp));//一定要新建一个数组加入结果集中
        return;
    }
    for(int i = level; i < candidates.length; i++) {            
        tmp.add(candidates[i]);
        findSum(candidates, target, sum+candidates[i], result, tmp, i);
        tmp.remove(tmp.size()-1);//需回退到上一个状态            
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值