排列组合算法实现
程序员文章站
2022-05-21 23:22:19
...
排列数:
#include <iostream>
using namespace std;
int n, k;
int a[25] = { 0 };
int b[25] = { 0 };
int vis[25] = { 0 };
void dfs(int step) {
if (step == k) {
for (int i = 0; i < k; i++)
cout << b[i] << " ";
cout << endl;
}
else {
for (int i = 0; i < n; i++)
if (vis[i] == 0) {
b[step] = a[i];
vis[i] = 1;
dfs(step + 1);
vis[i] = 0;
}
}
}
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
dfs(0);
return 0;
}
组合数:
#include <iostream>
using namespace std;
int n, k;
int a[25] = { 0 };
int b[25] = { 0 };
int vis[25] = { 0 };
void dfs(int step,int startx) {
if (step == k) {
for (int i = 0; i < k; i++)
cout << b[i] << " ";
cout << endl;
}
for (int i = startx; i < n; i++) {
if (vis[i] == 0) {
b[step] = a[i];
vis[i] = 1;
dfs(step + 1, i + 1);
vis[i] = 0;
}
}
}
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
dfs(0,0);
return 0;
}
上一篇: Steins——题解
下一篇: 排列组合问题