classSolution{ publicvoidbacktracking(List<List<Integer>> res, List<Integer> tmp, int k, int n, int start){ if (tmp.size() == k){ res.add(new ArrayList<Integer>(tmp)); return; } for (int i = start;i <= n - (k-tmp.size()) + 1; i++){ //notice i<=n-(k-tmp.size())+1 speed up from 26ms downto 2ms tmp.add(i); backtracking(res, tmp, k, n, i+1); tmp.remove(tmp.size()-1); } } public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); if (k>n) return res; backtracking(res, new ArrayList<Integer>(), k, n, 1); return res; } }