Simple Java solution 11 lines using backtracking


  • 0
    D

    public class Solution {

        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> ans=new ArrayList<>();
            backtrack(ans,new ArrayList<>(),1,k,n);
            return ans;
        }
        private void backtrack(List<List<Integer>> ans,List<Integer> cur,int start,int k,int n){
            if(n<0) return;
            if(k==0&&n==0){ans.add(new ArrayList<>(cur));return;}
            for(int i=start;i<=9;i++){
                cur.add(i);
                backtrack(ans,cur,i+1,k-1,n-i);
                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.