回溯法(3)

本文介绍了一种解决组合求和问题的算法实现。该算法针对一组候选数(不含重复),找出所有可能的组合,使这些组合中的数相加等于目标数。同一组中的数可以无限次重复使用。

原题:

/**
 * Created by pradhang on 3/14/2017.
 * Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
 * <p>
 * The same repeated number may be chosen from C unlimited number of times.
 * <p>
 * Note:
 * All numbers (including target) will be positive integers.
 * 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]
 * ]
 */

答案:


public class CombinationSum {
    /**
     * Main method
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int[] candidates = {2, 3, 6, 7};

        List<List<Integer>> result = new CombinationSum().combinationSum(candidates, 7);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> subList = new ArrayList<>();
        doNext(0, result, 0, candidates, target, subList);
        return result;
    }

    private void doNext(int i, List<List<Integer>> result, int count, int[] candidates, int target, List<Integer> subArr) {
        if (target == 0) {
            List<Integer> subList = new ArrayList<>();
            for (int k = 0; k < count; k++)
                subList.add(subArr.get(k));
            result.add(subList);
        } else if (target > 0) {
            for (int j = i, l = candidates.length; j < l; j++) {
                subArr.add(candidates[j]);
                doNext(j, result, count + 1, candidates, target - candidates[j], subArr);
                subArr.remove(subArr.size() - 1);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值