Straightforward Java recursive solution


  • 0
    Y
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if(k<1||k>9||n<k||n>9*k) return list;
        addToList(list,new ArrayList<Integer>(),1,k,n);
        return list;
    }
    private void addToList(List<List<Integer>> list, List<Integer> temp, int num, int k, int n){
        if(k==0||n==0){
            if(k==0&&n==0)
                list.add(new ArrayList<Integer>(temp));
            return;
        }
        for(int i=num;i<=10-k;i++){
            temp.add(i);
            addToList(list,temp,i+1,k-1,n-i);
            temp.remove(temp.size()-1);
        }
    }

Log in to reply
 

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