AcWing 93. 递归实现组合型枚举(递归解法、Java)
原题链接
简单
作者:
mzk
,
2020-04-02 16:36:31
,
所有人可见
,
阅读 579
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int n, m;
static int[] st = new int[100];
static void dfs(int u, int sum) {
// 边界条件
if (sum + n - u < m)//如果剩下的数凑不到m个
return;
if (sum == m) {
for (int i = 0; i < n; i++) {
if (st[i] == 1) {
System.out.print(i + 1 + " ");
}
}
System.out.println();
return;
}
st[u] = 1;//标志1表示选了这个数
dfs(u + 1, sum + 1);
st[u] = 0;//回溯,设为没选
dfs(u + 1, sum);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] read = br.readLine().split(" ");
n = Integer.parseInt(read[0]);
m = Integer.parseInt(read[1]);
dfs(0, 0);// 枚举到哪了,选了多少个
}
}