leecode---40---array, dfs---seek all combinations as target, there are repeating arrays

The input parameters of dfs are as follows: total result, current result, current sum, array, array subscript, target
If the current result>target exit directly
If ==target, record the result
If the sum is less than the target, it means that the number needs to be added at present, but the number that can be added can be added to the array from the pos position onwards. Because there may be repetitions here, if the current number and the previous number are repeated, continue skipping directly.
 
 
 

 
 
meaning of the title
Given an array and a target number, where the array has duplicates, find all the results combined as target
 
 
analyze
Backtracking. Sort the array first, and if it is repeated when traversing, just step over it.
Because numbers cannot be reused, you have to step over when backtracking.
 
 
code
class Solution {
    
    List<List<Integer>> result = new LinkedList<List<Integer>>();
    int target ;
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates == null || candidates.length <= 0 || target < 0) return result;
        this.target = target;
        Arrays.sort(candidates);
        backTrack(candidates,0,new LinkedList<Integer>(),0);
        return result;
    }
    
    //Backtracking method, during the backtracking process:
    //1. Direct return if the condition is not met, here curSum exceeds the target
    //2. Satisfaction is directly recorded in the global variable
    //3. Otherwise, continue to backtrack, remember to add and pop up when backtracking the record path
    public void backTrack(int[] nums,int curSum,List<Integer> temp,int start) {
        if (curSum > target) return;
        if (curSum == target) {
            result.add(new LinkedList(temp));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1])continue;
            temp.add(nums[i]);
            backTrack(nums,curSum + nums[i],temp,i + 1);
            temp.remove(temp.size() - 1);
        }
    }
}
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325220862&siteId=291194637