【题目】

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

【思路】

回溯,不同在可以重复使用当前元素。相关题目

1、[Leetcode 78]求子集 Subset https://www.cnblogs.com/inku/p/9976049.html

2、[Leetcode 90]求含有重复数的子集 Subset II https://www.cnblogs.com/inku/p/9976099.html

3、讲解在这: [Leetcode 216]求给定和的数集合 Combination Sum III

4、[Leetcode 39]组合数的和Combination Sum

【代码】

通俗版,重点在flag=i。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ans=new ArrayList<>();
        List<Integer> tmp=new ArrayList<>();
        fun(ans,tmp,candidates,0,target);
        return ans;
    }
    public void fun(List<List<Integer>> ans,List<Integer> tmp,int[] data,int flag,int aim){
        if(aim<0)return;
        else if(aim==0)
            ans.add(new ArrayList<>(tmp));
        else{
            for(int i=flag;i<data.length;i++){
                tmp.add(data[i]);
                fun(ans,tmp,data,i,aim-data[i]);
                tmp.remove(tmp.size()-1);
            }
        }
    }
}

改进,ans设为全局变量,两个判断合并成一次

class Solution {
    private static List<List<Integer>> res ;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        helper(candidates , 0 , target , new ArrayList<>());
        return res;
        
    }
    private void helper(int[] input , int index , int target, List<Integer> temp) {
        if (target<= 0) {
            if (target == 0) {
                res.add(new ArrayList<>(temp));
            }
            return ;
        }
        for (int i = index ; i < input.length ; i++) {
            temp.add(input[i]);
            helper(input , i , target - input[i] , temp);
            temp.remove(temp.size() - 1);
        }
    }
}

 

 posted on 2018-11-30 22:10  alau  阅读(148)  评论(0编辑  收藏  举报