39. Combination Sum(Medium)(DFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/86993580

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

如何防止重复是本题关键

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new LinkedList<>();
        Arrays.sort(candidates);
        dfs(ans, new LinkedList<Integer>(), 0, 0, candidates, target);
        return ans;
    }
    
    public void dfs(List<List<Integer>> ans, List<Integer> list, int sum, int start, int[] candidates, int target){
        if (sum == target){
            //ans.add(list);   又犯错误
            ans.add(new LinkedList<Integer>(list));
            return;
        }else{
            for (int i = start; i<candidates.length; i++){
                if (sum+candidates[i] > target) break;
                list.add(candidates[i]);
                dfs(ans, list, sum+candidates[i], i, candidates, target);
                list.remove(list.size()-1);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/86993580