题目
输入两个整数 n 和 m,从数列1,2,3…n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来
思路
1.用dfs的思想,n=5 m=5 如下图遍历得到count==0的情况只有以下框出来的两种。
代码
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
static ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> list = new ArrayList<>();
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n, m;
while(sc.hasNext()) {
n = sc.nextInt();
m = sc.nextInt();
dfs(1, m, n);
for(ArrayList<Integer> l : res) {
int i = 0;
for(; i < l.size() - 1; i++) {
System.out.print(l.get(i) + " ");
}
System.out.println(l.get(i));
}
}
}
public static void dfs(int index, int count, int n) {
//出口
if(count == 0) {
res.add(new ArrayList<>(list));
}
else {
for(int i = index; i <= count && i <= n; i++) {
list.add(i);//添加路线
dfs(i + 1, count - i, n);
list.remove(list.size() - 1);//回溯
}
}
}
}
总结
1.dfs的理论