Special backtracking Leetcode of -216. The total composition III (Combination Sum III) Leetcode law of backtracking thematic -39. Special Leetcode of backtracking Total (Combination Sum) -40 composition. Total composition II (Combination Sum II)

Special backtracking Leetcode of -216. The total composition III (Combination Sum III)

Similar topics:

Thematic backtracking Leetcode of -39. The total number of combinations (Combination Sum)

Special backtracking Leetcode of -40. The total composition II (Combination Sum II)


 

 

And find all the sum of  of  combination number . Composition may only contain 1-- 9 positive integer, and repeatable number does not exist in each combination.

Description:

  • All numbers are positive integers.
  • Solution Set can not contain duplicate combinations thereof. 

Example 1:

Input: K =. 3, n- =. 7 
Output: [[2,4]]

Example 2:

Input: K =. 3, n- =. 9 
Output: [[1,2,6], [1,3,5], [2,3,4]]


Analysis:
are two questions before the upgrade, link two questions before the beginning of the article.

Given k and n, seeking 1-9, taking the number of k, and allow them to n.

Similarly, backtracking, is divided into two branches taken and not taken, and in the plus and judgment as well as the determination of the number taken.

class Solution {
    
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        if(k==0 || n==0) return ans;
        dfs(k,n,1,new ArrayList<Integer>(),0);
        return ans;
    }
    public void dfs(int k,int n,int step,ArrayList<Integer> list,int sum){
        if(list.size()==k && sum==n){
            ans.add(new ArrayList<>(list));
            return;
        }
        if(step>9) return;
        
        
        
        list.add(step);
        dfs(k,n,step+1,list,sum+step);
        list.remove(list.size()-1);
        dfs(k,n,step+1,list,sum);
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11330214.html