Simple Java Recursive solution


  • 2
    J
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            recur(new ArrayList<Integer>(),res,n,1,k);
            return res;
        }
        public void recur(List<Integer> temp,List<List<Integer>> res, int tar,int k,int count){
            if(tar==0&&count==0){
                res.add(temp);
                return;
            }
            if(count==0||tar<=0)return;
            
            for(int i=k;i<=9;i++){
                temp.add(i);
                recur(new ArrayList<Integer>(temp),res,tar-i,i+1,count-1);
                temp.remove(temp.size()-1);
            }
        }
    }

  • 0
    S

    On the recursive call, why do you have to build a new ArrayList when calling itself recursively?


  • 0
    J

    Cause if not, the subsequent operations would change the objects(ArrayList) and the result would be wrong. Actually, you can also do this when adding the object into result list(line 9).


Log in to reply
 

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