题目描述
给定不超过6的正整数A,考虑从A开始的连续4个数字。请输出所有由它们组成的无重复数字的3位数。
输入
输入在一行中给出A。
输出
输出满足条件的的3位数,要求从小到大,每行6个整数。整数间以空格分隔,但行末不能有多余空格。
样例输入
2
样例输出
234 235 243 245 253 254
324 325 342 345 352 354
423 425 432 435 452 453
523 524 532 534 542 543
思路
两个思路
1.用next_permutation枚举存入set后再输出
2.类似dfs
思路一 代码
#include <bits/stdc++.h>
using namespace std;
set<int> st;
int a[3];
int main(){
int n;
cin>>n;
a[0] = n;
a[1] = n+1;
a[2] = n+2;
do{
st.insert(a[0]*100+a[1]*10+a[2]);
}while(next_permutation(a, a+3));
a[0] = n;
a[1] = n+1;
a[2] = n+3;
do{
st.insert(a[0]*100+a[1]*10+a[2]);
}while(next_permutation(a, a+3));
a[0] = n;
a[1] = n+2;
a[2] = n+3;
do{
st.insert(a[0]*100+a[1]*10+a[2]);
}while(next_permutation(a, a+3));
a[0] = n+1;
a[1] = n+2;
a[2] = n+3;
do{
st.insert(a[0]*100+a[1]*10+a[2]);
}while(next_permutation(a, a+3));
int cnt = 0;
for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
if(cnt){
cout<<' ';
}
cout<<*it;
if(++cnt%6 == 0){
cnt = 0;
cout<<endl;
}
}
return 0;
}
思路二 代码
#include <bits/stdc++.h>
using namespace std;
int book[10];
int main(){
int a;
int cnt = 0;
cin>>a;
int i, j, k;
for(i=a; i<a+4; i++){
book[i] = 1;
for(j=a; j<a+4; j++){
if(book[j] == 0){
book[j] = 1;
for(k=a; k<a+4; k++){
if(book[k] == 0){
book[k] = 1;
if(cnt){
cout<<' ';
}
cout<<i<<j<<k;
if(++cnt==6){
cnt = 0;
cout<<endl;
}
book[k] = 0;
}
}
book[j] = 0;
}
}
book[i] = 0;
}
return 0;
}