Java Backtrack solution


  • 0
    X
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            combine(k,n,1,new LinkedList<Integer>(),res);
            return res;
            
            
        }
        
        public void combine(int num, int target, int index, List<Integer> cur, List<List<Integer>> res){
            if (num < 0 || target < 0)
                return;
                
            if (num == 0){
                if (target == 0){
                    LinkedList<Integer> l = new LinkedList<Integer>(cur);
                    res.add(l);
                }
                return;
            }
            
            for (int i = index; i <= 9; i++){
                    cur.add(i);
                    combine(num-1,target-i,i+1,cur,res);
                    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.