排列输出
全排列问题
题目描述
按照字典序输出自然数 1 1 1 到 n n n 所有不重复的排列,即 n n n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
输入格式
一个整数 n n n。
输出格式
由 1 ∼ n 1 \sim n 1∼n 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 5 5 5 个场宽。
样例 #1
样例输入 #1
3
样例输出 #1
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
提示
1 ≤ n ≤ 9 1 \leq n \leq 9 1≤n≤9。
代码模板
#include<iostream>
#include<iomanip>
using namespace std;
const int N = 15;
int w[N];
bool st[N];
int n;
//防止向后用last(也就是求组合),防止重复用st数组(也就是求排列数)
void dfs(int u,int last){
if(u==n){
for(int i=0;i<n;i++){
cout<<setw(5)<<w[i];
}
cout<<endl;
return;
}
for(int i=1;i<=n;i++){
if(!st[i]){//判重还是st数组好用
st[i]=true;
w[u]=i;
dfs(u+1,i+1);
w[u]=0;
st[i]=false;
}
}
}
int main(){
cin>>n;
dfs(0,1);
return 0;
}
组合
组合的输出
题目描述
排列与组合是常用的数学方法,其中组合就是从 n n n 个元素中抽出 r r r 个元素(不分顺序且 r ≤ n r \le n r≤n),我们可以简单地将 n n n 个元素理解为自然数 1 , 2 , … , n 1,2,\dots,n 1,2,…,n,从中任取 r r r 个数。
现要求你输出所有组合。
例如 n = 5 , r = 3 n=5,r=3 n=5,r=3,所有组合为:
123 , 124 , 125 , 134 , 135 , 145 , 234 , 235 , 245 , 345 123,124,125,134,135,145,234,235,245,345 123,124,125,134,135,145,234,235,245,345。
输入格式
一行两个自然数 n , r ( 1 < n < 21 , 0 ≤ r ≤ n ) n,r(1<n<21,0 \le r \le n) n,r(1<n<21,0≤r≤n)。
输出格式
所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,每个元素占三个字符的位置,所有的组合也按字典顺序。
注意哦!输出时,每个数字需要 3 3 3 个场宽。以 C++ 为例,你可以使用下列代码:
cout << setw(3) << x;
输出占
3
3
3 个场宽的数
x
x
x。注意你需要头文件 iomanip
。
样例 #1
样例输入 #1
5 3
样例输出 #1
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
代码模板
#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;
const int N = 22;
int w[N];
int n,m;
void dfs(int u,int last){
if(u==m){
for(int i=0;i<m;i++){
cout<<setw(3)<<w[i];
}
cout<<endl;
return;
}
for(int i=last;i<=n;i++){
w[u]=i;
dfs(u+1,i+1);
w[u]=0;
}
}
int main(){
cin>>n>>m;
dfs(0,1);
return 0;
}
总结
一般来说,对于dfs的参数,防止向后用last(也就是求组合),防止重复用st数组(也就是求排列数)