public class Main {
public static List<List<Integer>> result = new ArrayList<>();
public static List<Integer> path = new ArrayList<>();
public static void main(String[] args) {
int n = 4;
int k = 2;
combine(4, 2);
System.out.println(result);
}
public static List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1);
return result;
}
public static void backtracking(int n, int k, int startindex) {
if (path.size() == k) {
List<Integer> tmp = new ArrayList<>(path);//每次path符合要求后,把path的值放到临时变量tmp里,再放到result里。此时保持path容器唯一,去做装值、递归的操作。不能直接用result.add(path)
result.add(tmp);
return;
}
for (int i = startindex; i <= n; i++) {
path.add(i);
backtracking(n, k, i + 1);
path.remove(path.size() - 1);//去除最后一个值(回溯思想)
}
}
}
减支版本
public class Main {
public static List<List<Integer>> result = new ArrayList<>();
public static List<Integer> path = new ArrayList<>();
public static void main(String[] args) {
int n = 4;
int k = 2;
combine(4, 2);
System.out.println(result);
}
public static List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1);
return result;
}
public static void backtracking(int n, int k, int startindex) {
if (path.size() == k) {
List<Integer> tmp = new ArrayList<>(path);//每次path符合要求后,把path的值放到临时变量tmp里,再放到result里。此时保持path容器唯一,去做装值、递归的操作。不能直接用result.add(path)
result.add(tmp);
return;
}
for (int i = startindex; i <= n-(k-path.size())+1; i++) {//减支操作
path.add(i);
backtracking(n, k, i + 1);
path.remove(path.size() - 1);//去除最后一个值(回溯思想)
}
}
}