leetcode216 (combined sum III: binary enumeration)

Find all the combinations of k numbers that add up to n. Only positive integers from 1 to 9 are allowed in the combination, and there are no repeated numbers in each combination.

Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]

Solution (1): The total number of enumerations for this question is no more than 2^9. We can directly traverse each combination to find the combination that meets the requirements. When enumerating, we can use binary enumeration, using binary numbers to help us traverse all the combinations. For this question, it is a nine-digit binary number. If the number on a certain digit is 1, then select the digit of the digit; if it is 0, the digit of that digit is not selected (for example: 000001101, it means Combination of numbers [1,3,4])

class Solution {
    
    
     private final List<Integer>tempList=new Vector<>();
     private final List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
    
    
          //0~1	<<9中的每一个数字的二进制形式都代表了一种组合情况
          for(int mask=0;mask<(1<<9);mask++){
    
    
              if(checkSum(mask,n, k))
                  res.add(new ArrayList<>(tempList));
          }
          return res;
    }
    private boolean checkSum(int mask,int n,int k){
    
    
        tempList.clear();
        for(int i=0;(1<<i)<mask;i++){
    
    
            //判断二进制数字第i+1位的数字是否为1
            if(((1<<i)&mask)!=0)
                tempList.add(i+1);
        }
        int sum=0;
        for(int x:tempList)
            sum+=x;
        return sum==n&&tempList.size()==k;
    }
}

Problem solution (two): backtracking method
(the specific method of the algorithm is analogous to Leetcode39 (combined sum I) and Leetcode40 (combined sum II) )

class Solution {
    
    
     private final Stack<Integer>stack=new Stack<>();
     private final List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
    
    
             backTrace(1,n,0,k,0);
             return res;
    }
    private void backTrace(int min,int n,int sum,int k,int size){
    
    
        if(n-sum<min||size>k)
            return;
        if(size==k-1){
    
    
            if(n-sum>=min&&n-sum<=9&&n-sum>=0)  {
    
    
                stack.push(n - sum);
                res.add(getArray(stack));
                stack.pop();
            }
            return;
        }
        for(int i=min;i<=9;i++){
    
    
            stack.push(i);
            backTrace(i+1,n,sum+i,k,size+1);
            stack.pop();
        }
    }
    private List<Integer> getArray(Stack<Integer>stack){
    
    
        return new ArrayList<>(stack);
    }
}

Guess you like

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