My Java solution


  • 0
    S

    My java solution. No backtracking?
    {

    public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        return combination(k,n,9);
    }
    
    public List<List<Integer>> combination(int k, int n, int max){
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> ans = new ArrayList<Integer>();
        if(k == 1){ 
            if(n<=max && n>=1){
                ans.add(n);
                list.add(ans);
            }
        }else if(k>1){
            for(int i = max;i>=1;i--){
                if(n>=i){
                    List<List<Integer>> tmpList = combination(k-1,n-i,i-1);
                    for(int j = 0;j< tmpList.size();j++){
                        tmpList.get(j).add(i);
                        list.add(tmpList.get(j));
                    }
                }else break;
            }
        }
        return list;
    }
    }
    

    }


Log in to reply
 

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