public List<List<Integer>> combine(int n, int k) { List<List<Integer>> list = new ArrayList<>(); backtrack(list, new ArrayList<>(), n, k, 1); return list; }
privatevoidbacktrack(List<List<Integer>> list , List<Integer> tempList, int n,int k, int start){ if(tempList.size()==k){ list.add(new ArrayList<>(tempList)); } else{ for(int i = start; i <=n ;i++){ tempList.add(i); backtrack(list, tempList, n,k, i + 1); tempList.remove(tempList.size() - 1); } } }
public List<List<Integer>> combine(int n, int k) { List<List<Integer>> list = new LinkedList<>(); backtrack(list,n,k,1,new ArrayList<Integer>()); return list; } privatevoidbacktrack(List<List<Integer>> list, int n, int k, int start, List<Integer> tempList){ if(k==0) { list.add(new LinkedList<>(tempList)); return; } for(int i = start;i<=n-k+1;i++){ tempList.add(i); backtrack(list,n,k-1,i+1,tempList); tempList.remove(tempList.size()-1); } }