39. 组合总和 Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150combinations for the given input.

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

 

方法:

回溯+递归

保持查找顺序往后,即可去重

 

public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> one = new ArrayList<>();
        for(int i = 0 ; i < candidates.length; i++){
            one.add(candidates[i]);
            backTrace(candidates,target- candidates[i],ans,one,i);
            one.remove(one.size()-1);
        }
        return ans;
    }
    public void backTrace(int[] candidates, int target,List<List<Integer>> ans,List<Integer> one,int begin){
        if (target ==0) {
            ans.add(new ArrayList<Integer>(one));
        }
        else if(target<0) return;
        for (int i = begin ; i < candidates.length; i++){
            one.add(candidates[i]);
            backTrace(candidates,target- candidates[i],ans,one,i );
            one.remove(one.size()-1);
        }
    }

 

参考链接:

https://leetcode.com/problems/combination-sum/

https://leetcode-cn.com/problems/combination-sum/

posted @ 2020-12-18 16:41  diameter  阅读(87)  评论(0编辑  收藏  举报