[LeetCode - 回溯] 39. Combination Sum

1 问题

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.
The same repeated number may be chosen from C unlimited number of times.
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]
]

2 分析

如果对输入不做处理,所有可能出现的数字组合有 C1n+C2n+...+Cnn 种,将其中每一个与target比较,时间复杂度是指数级别的。
但是该问题蕴含着数字的大小、相等关系,因此需要利用这种内在的数字关系来提高算法的运行效率。
为此,将输入的数组进行排序,排序算法的时间复杂度是 O(nlogn) 。排序之后,整个解法的计算过程如图所示:
递归树
设输入的数组用 a1,a2,...,an 表示。上图中,树的结点表示所有可能与target相等的组合,层数等于可能的组合中的数字个数。令 Sn 表示每个节点中所有元素的和,因此:

  • 如果 Sntarget 该节点存在子节点,继续按照图示规律访问子节点;
  • 如果 Sn>target ,该节点为叶子,应当回溯回父节点。

在所有可能的组合遍历完成后,与target相等的组合会被记录下来。
该算法的时间复杂度为树中所有节点的数目,与题目所给输入值有关。

3 代码

递归+回溯:

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        getResult(result, new ArrayList<Integer>(), candidates, target, 0);
        return result;
    }

    private boolean getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
        if(target == 0){
            result.add(new ArrayList<Integer>(cur));
            return true;
        }else if(target < 0){
            return false;
        }else{
            for(int i = start; i < candidates.length && target >= candidates[i]; i++){
                cur.add(candidates[i]);
                boolean res = getResult(result, cur, candidates, target - candidates[i], i);
                if(!res){
                    return false;
                }
                cur.remove(cur.size() - 1);
            }
            return true;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值