LeetCode - Combination Sum

https://leetcode.com/problems/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:

  • 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] 

这道题是典型的递归求解,对于这种要求所有解的题都可以用递归做。

题目中要求返回的解中的值是递增的,因此应该先对数组排序。另外,要求不能有重复解,由于每一层递归对应解中的一个位置,因此每层递归中(即对应的解的位置)不能有相同的值,因此用一个while循环来避免这种重复。还有一种重复是如[1,2]和[2,1]这种的,就是每个位置的值不一样,但其实只是顺序不同,本质是一样的。这种重复的情况是用确定一个位置后,它后面的位置上的数都必须只找比它大的数来解决的。因此helper有个start参数,来规定只再上一个数本身以及它后面的数中来寻找后面的位置的解。


代码如下:

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> rst = new LinkedList<List<Integer>>();
        if(candidates==null || candidates.length==0) return rst;
        Arrays.sort(candidates);  //保证解中的数是递增排列的
        List<Integer> solution = new LinkedList<Integer>();
        
        helper(candidates, rst, solution, target, 0);
        
        return rst;
    }
    
    public void helper(int[] candidates, List<List<Integer>> rst, List<Integer> solution, int target, int start){
        if(target==0){
            rst.add(new LinkedList<Integer>(solution));
            return;
        }
        if(target<0) return;
        for(int i=start; i<candidates.length; i++){    //start参数规定后面位置上的解不能再用在当前位置之前的数,避免[1,2], [2,1]这种重复
            solution.add(candidates[i]);
            helper(candidates, rst, solution, target-candidates[i], i);
            solution.remove(solution.size()-1);
            while(i<candidates.length-1 && candidates[i+1]==candidates[i]) i++;   //一个位置上不能有相同的值
        }
    }
}

时间复杂度应该是NP的,第一层递归O(n),第二层O(n*(n-1))...以此类推,因此是n+n^2+n^3+....,因此时间复杂度是exponential的。

空间复杂度是调用递归的次数,应该是n+n(n-1)+.....,空间复杂度也是exponential的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值