leetcode39 (combination sum: backtracking method)

Given an array of candidates with no duplicate elements and a target number target, find out all combinations of candidates that can make the sum of the numbers target.
The numbers in candidates can be repeatedly selected without limitation.

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

Problem solution: fast sorting + backtracking. For the problem of enumeration + combination, we can all use the backtracking method to solve the problem. This problem is just to increase the filtering limit to the enumeration result of the enumeration method-making the enumeration combination in The numbers add up to the target. We only need to determine that the sum of all current numbers is equal to target in the process of backtracking. When using the backtracking method, we use fast sorting to sort the array to make the backtracking more orderly.

class Solution {
    
    
    private  final Stack<Integer>stack=new Stack<>();
    private  final List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
    
    
          Solution.sort(candidates);
          backTrace(candidates,target,0,0);
          return res;
    }
    //回溯算法进行枚举+组合
    private void backTrace(int[]candidates,int target,int min,int sum){
    
    
        if(sum==target)
            res.add(new ArrayList<>(stack));
        else if(target-sum<candidates[min])
            return;
        int len=candidates.length;
       
        for(int i=min;i<len;i++){
    
    
            if(sum+candidates[i]<=target) {
    
    
                stack.push(candidates[i]);
                backTrace(candidates,target,i,sum+candidates[i]);
                stack.pop();
            }
            else
                return;
        }
    }

    //快排算法
    public static void sort(int[]args){
    
    
        quickSort(args,0,args.length-1);
    }
    private static void quickSort(int[]args,int start,int end){
    
    
        if(start>=end)
            return;
        int pivot=args[start];
        int left=start;
        int right=end;
        while(left<right){
    
    
            while(args[right]>pivot&&left<right)
                right--;
            while(args[left]<=pivot&&left<right)
                left++;
            change(args,right,left);
        }
        change(args,start,left);
        quickSort(args,start,left-1);
        quickSort(args,left+1,end);
    }
    private static void change(int[]args,int x,int y){
    
    
        int temp=args[x];
        args[x]=args[y];
        args[y]=temp;
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108494060