题目链接:
代码:
排列:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10;
int n;
bool vis[maxn];
vector<int> tmp;
void dfs(int count){
if(count == n){
for(int i:tmp){
cout << " "<<i;
}
cout << '\n';
}
for(int i=1; i<=n; i++){
if(vis[i]) continue;
vis[i] = true;
tmp.push_back(i);
dfs(count+1);
vis[i] = false;
tmp.pop_back();
}
}
int main(){
cin >> n;
memset(vis, false, sizeof(vis));
dfs(0);
}
或者调stl也可
#include <bits/stdc++.h>
using namespace std;
int n;
int arr[10];
int main(){
cin >> n;
for(int i=1; i<=n; i++){
arr[i] = i;
}
do{
for(int i=1; i<=n; i++){
cout << " " << arr[i];
}
cout << '\n';
} while(next_permutation(arr+1, arr+n+1));
}
组合:
#include <bits/stdc++.h>
using namespace std;
int n, m;
int tmp[23];
void dfs(int cnt, int cur){
if(cnt == m){
for(int i=0; i<m; i++) printf("%3d", tmp[i]); //格式输出,占三个字符位
cout << '\n';
return;
}
for(int i=cur; i<=n; i++){
tmp[cnt] = i;
dfs(cnt+1, i+1);
tmp[cnt] = 0;
}
}
int main(){
cin >> n >> m;
dfs(0,1);
}