您的位置:首页 > 其它

递归实现全排列(按字典序)

2018-01-29 17:49 176 查看
codeup.cn 算法笔记习题 https://github.com/ultraji/codeup

/*
问题 A: 全排列

题目描述
排列与组合是常用的数学方法。
先给一个正整数 ( 1 < = n < = 10 )

例如n=3,所有组合,并且按字典序输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

输入
输入一个整数n(  1<=n<=10)

输出
输出所有全排列
每个全排列一行,相邻两个数用空格隔开(最后一个数后面没有空格)

样例输入
3

样例输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/

#include <iostream>
#include <algorithm>
using namespace std;

void show(int a[],int len){
for(int i = 0; i < len - 1; i++){
printf("%d ", a[i]);
}
printf("%d\n",a[len-1]);
}

int hash_map[10] = {0}; //hash数组用来标记哪些数字已经被使用过
int b[10] = {0};
int j = 0;
void my_next_permutation(int a[],int len){
for(int i = 0; i < len; i++){
for(;hash_map[i] == 1;i++);    //始终从小到大使用 没使用过的数字
if(i != len){
hash_map[i] = 1;
b[j++] = a[i];
if(j == len) show(b,len);
my_next_permutation(a,len);
j--;
hash_map[i] = 0;
}
}
}

int main(){
int a[10]={1,2,3,4,5,6,7,8,9,10},n;
while(cin >> n){
my_next_permutation(a,n);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: