问题描述
0、1、2三个数字的全排列有六种,按照字母序排列如下:
012、021、102、120、201、210
输入一个数n
求0~9十个数的全排列中的第n个(第1个为0123456789)。
输入格式
一行,包含一个整数n
输出格式
一行,包含一组10个数字的全排列
样例输入
1
样例输出
0123456789
数据规模和约定
0 < n <= 10!
分析:啊我才发现有一个超好用的库函数……完全不用自己实现全排列。。竟然自己还那么笨的用下面的深度优先搜索的办法……next_permutation函数。。在algorithm里面,代码如下:
#include
#include
using namespace std;
int main() {
string s = "0123456789";
int n;
cin >> n;
int cnt = 1;
do {
if(cnt == n) {
cout << s;
break;
}
cnt++;
}while(next_permutation(s.begin(), s.end()));
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include
#include
usingnamespacestd;
intmain(){
strings="0123456789";
intn;
cin>>n;
intcnt=1;
do{
if(cnt==n){
cout<
break;
}
cnt++;
}while(next_permutation(s.begin(),s.end()));
return0;
}
下面是那个笨方法。。。
假设有10个位置,需要在10个位置上依次放置0~9这十个数字。
1.先走到第一个位置,此时放置一个当前可以放置的数字当中最小的那个数字。
2.在走到第二个位置,放置一个当前可以放置的数字当中最小的那个数字。
…
3.到第10个位置时候,所有的数字已经放置完毕,属于第一个全排列。
4.收回第10个位置上的数字,此时还是只可以放置9,那么再到第9个位置面前,收回位置上的数字。
5.在第9个位置处,我们此时可以放置的数字有9,那么第10个位置放8.属于第二个全排列。
6.收回第10、9、8位置的数字,此时可以在第8个位置放置8.
…
用一个数组标记当前的数字是否已经被使用过了。
int book[10]; //一开始的时候没有被使用,初始化值为0.使用过了之后标记为1.
int a[10]; // 表示这10个需要放置数字的位置。
深度优先搜索:
void dfs(int step) {
for (int i = 0; i <= 9; i++) {
if (book[i] == 0) { //如果当前数字i没有被使用过
a[step] = i; //就把当前位置放上这个数字i
book[i] = 1; //同时不要忘记把book[i]标记为1
dfs(step + 1); //深度优先搜索下一步
book[i] = 0; //表示收回当前的数字
}
}
}
还有一个循环出口没有写。从step = 0开始执行,当当前的步骤已经step == 10的时候,
因为我们需要考虑的是0~9位置的摆放数字情况,当step时候不用执行,可以return作为出口了。
因为题目要求我们输出第n个全排列的组合是什么,那么
int cou = 0;
每当 step == 10 一组全排列完成的时候,
cou++;
直到 cou == n 的时候输出a数组中所有的数字。
所以代码描述为:
if (step == 10) {
cou++;
if (cou == n) {
for (int i = 0; i <= 9; i++) {
cout << a[i];
}
}
return;
}
该题的解答完整代码如下:
#include
using namespace std;
int n;
int book[10];
int a[10];
int cou = 0;
void dfs(int step) {
if (step == 10) {
cou++;
if (cou == n) {
for (int i = 0; i <= 9; i++) {
cout << a[i];
}
}
return;
}
for (int i = 0; i <= 9; i++) {
if (book[i] == 0) {
a[step] = i;
book[i] = 1;
dfs(step + 1);
book[i] = 0;
}
}
}
int main() {
cin >> n;
dfs(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
voiddfs(intstep){
for(inti=0;i<=9;i++){
if(book[i]==0){//如果当前数字i没有被使用过
a[step]=i;//就把当前位置放上这个数字i
book[i]=1;//同时不要忘记把book[i]标记为1
dfs(step+1);//深度优先搜索下一步
book[i]=0;//表示收回当前的数字
}
}
}
还有一个循环出口没有写。从step=0开始执行,当当前的步骤已经step==10的时候,
因为我们需要考虑的是0~9位置的摆放数字情况,当step时候不用执行,可以return作为出口了。
因为题目要求我们输出第n个全排列的组合是什么,那么
intcou=0;
每当step==10一组全排列完成的时候,
cou++;
直到cou==n的时候输出a数组中所有的数字。
所以代码描述为:
if(step==10){
cou++;
if(cou==n){
for(inti=0;i<=9;i++){
cout<
}
}
return;
}
该题的解答完整代码如下:
#include
usingnamespacestd;
intn;
intbook[10];
inta[10];
intcou=0;
voiddfs(intstep){
if(step==10){
cou++;
if(cou==n){
for(inti=0;i<=9;i++){
cout<
求第n个全排列
本文介绍两种方法求解0~9数字的第n个全排列:一是利用STL库函数next_permutation,二是采用深度优先搜索算法。通过具体实例展示算法流程及C++代码实现。

被折叠的 条评论
为什么被折叠?



