Share my simple Java Solution with backtracking


  • 0
    X
    public class Solution {
        List<List<Integer>> res; 
        List<Integer> curRes; 
    
        public void backTrack(int k, int target, int lastNum){
            if(target == 0 && k == 0){
                res.add(new ArrayList<Integer>(curRes));
            }else if(target < 0 || k < 0){
                return;
            }else{
                int i = lastNum; 
                while( k > 0 && i < 10){
                    curRes.add(i);
                    backTrack(k-1, target - i, i+1);
                    curRes.remove(curRes.size()-1);
                    i++;
                }
            }
        }
        
        public List<List<Integer>> combinationSum3(int k, int n) {
            res = new ArrayList<List<Integer>>();
            curRes = new ArrayList<Integer>();
            backTrack(k, n, 1);
            return res;
        }
    }

Log in to reply
 

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