代码很相近,只需稍微改动即可在排列与组合中切换
组合
import java.io.IOException;
import java.util.Scanner;
class MC {
int N = 10;
int[] a = new int[N];
boolean[] st = new boolean[N];
//C(k1, k2)
int k1 = 9, k2 = 2;
void check() {
for (int i = 1; i <= k2 ; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
void dfs(int cnt) {
if (cnt == k2 + 1){
check();
return;
}
for (int i = 1; i <= k1; i++) {
if (st[i] || i < a[cnt - 1]) continue;
st[i] = true;
a[cnt] = i;
dfs(cnt + 1);
st[i] = false;
}
}
public void run() throws IOException {
dfs(1);
}
Scanner sc = new Scanner(System.in);
}
public class Main {
public static void main(String[] args) throws IOException {
new MC().run();
}
}
排列
改动点:
1. 让k1与k2相等
2. 去掉i < a[cnt - 1]
import java.io.IOException;
import java.util.Scanner;
class MC {
int N = 10;
int[] a = new int[N];
boolean[] st = new boolean[N];
//A(k1, k2)
int k1 = 3, k2 = 3;
void check() {
for (int i = 1; i <= k2 ; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
void dfs(int cnt) {
if (cnt == k2 + 1){
check();
return;
}
for (int i = 1; i <= k1; i++) {
if (st[i]) continue;
st[i] = true;
a[cnt] = i;
dfs(cnt + 1);
st[i] = false;
}
}
public void run() throws IOException {
dfs(1);
}
Scanner sc = new Scanner(System.in);
}
public class Main {
public static void main(String[] args) throws IOException {
new MC().run();
}
}
牛啊,太强了