Java backtrack


  • 0
    J
        private List<List<Integer>> ans = new ArrayList<List<Integer>>();
        public List<List<Integer>> combine(int n, int k) {
            int s = 1;
            List<Integer> subl = new ArrayList<Integer>();
            helper(s,n,k,subl);
            return ans;
        }
        public void helper(int s, int n, int k, List<Integer> subl){
            if(k == 0){
                ans.add(new ArrayList<Integer>(subl));//IMPORTANT
                return;
            }
            for(int i = s; i <= n - k + 1; i++){
                subl.add(i);
                helper(++s,n,k-1,subl);//++s!!!
                //IMPORTANT
                subl.remove(subl.size() - 1);
            }
        }

Log in to reply
 

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