classSolution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> ans = newLinkedList<>(); List<Integer> path = newLinkedList<>(); myCombine(ans, path, n, k, 1); return ans; }
// for instance, n = 20, K = 3, // the tartet ans is the combination of every 2 elements in [1, 20] privatevoidmyCombine(List<List<Integer>> ans, List<Integer> path, int n, int k, int index) { // recursion exits if (path.size() == k) { List<Integer> combine = newLinkedList<>(); combine.addAll(path); ans.add(combine); return; } // this is to remove those unvalid recursion for (inti= index; i <= n - (k - path.size()) + 1 ; i++) { path.add(i); myCombine(ans, path, n, k, i + 1); path.remove(path.get(path.size() - 1));