Java solution using backtracking


  • 0
    U
    public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        getResult(result, new ArrayList<Integer>(), k, n, 1);
        return result;
    }
    
    private void getResult(List<List<Integer>> result, List<Integer> cur, int k, int target, int start){
        if(target == 0 && cur.size()==k ){
            result.add(new ArrayList<Integer>(cur));
            return;
        } 
        else if(target>0){
            for(int i = start; i <= 9 && i<=target; i++){
                cur.add(i);
                getResult(result, cur, k, target - i, i+1);
                cur.remove(cur.size() - 1);
            }
        }
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.