Don't know how else to simplify solution Java backtracking


  • 0
    T
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> result = new ArrayList<>();
            if(n==0 || k>n) return result;
            helper(1, n, k, new ArrayList<Integer>(), result);
            return result;
        }
        
        private void helper(int index, int n, int k, List<Integer> list, List<List<Integer>> result){
            if(k==0){
                result.add(new ArrayList<Integer>(list));
                return;
            }
            for(int i = index;i<=n;i++){
                list.add(i);
                helper(i+1, n, k-1, list, result);
                list.remove(list.size()-1);
            }
        }
    }

Log in to reply
 

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