LeetCode 39. Combination Sum 组合总和 (C++/Java)

题目:

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

分析:

给定一个无重复元素的数组,要求用数组中的元素构成组合(可以重复),使元素和与target相同,且最后答案中不能有重复的组合。

利用深度优先搜索,在搜索的时候要传入一个索引,递归搜素时,从当前索引处向后搜索元素,防止最后有重复的元素组合,同时每搜索到一个元素,使当前目标修改为target-元素,当目标为0时,代表我们找到了一个解,加入到结果集合中。

可以先将所有元素由小到大排序,当搜索过程中当前元素大于目标值,此时后面的所有元素都不符合要求,提前退出循环。

程序:

C++

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> curr;
        sort(candidates.begin(), candidates.end());
        dfs(res, curr, target, 0, candidates);
        return res;
    }
    void dfs(vector<vector<int>>& res, vector<int> curr, int target, int index, vector<int>& candidates){
        if(target == 0){
            res.push_back(curr);
            return;
        }
        for(int i = index; i < candidates.size(); ++i){
            if(candidates[i] > target)
                break;
                //continue;
            curr.push_back(candidates[i]);
            dfs(res, curr, target-candidates[i], i, candidates);
            curr.pop_back();
        }
    }
};

Java

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new LinkedList<>();
        LinkedList<Integer> curr = new LinkedList<>();
        Arrays.sort(candidates);
        dfs(res, curr, target, 0, candidates);
        return res;
    }
    private void dfs(List<List<Integer>> res, LinkedList<Integer> curr, int target, int index, int[] candidates){
        if(target == 0){
            res.add(new LinkedList<>(curr));
            return;
        }
        for(int i = index; i < candidates.length; ++i){
            if(candidates[i] > target)
                break;
            curr.addLast(candidates[i]);
            dfs(res, curr, target-candidates[i], i, candidates);
            curr.removeLast();
        }
    }
}

 

posted @ 2020-02-24 16:46  silentteller  阅读(326)  评论(0编辑  收藏  举报