输出1-n的所有全排列

#include<cstdio>
#define maxn 20
#include<algorithm>
#include<vector>
using namespace std;
//n个数的全排列等于第一个位置选x,剩下的位置是n-1个数除去x的全排列,这是递归式
//递归出口最后一个位置只有一个可选
//用for循环实现某个位置上1到n的遍历
//哈希表记录某个数当前是否在排列中
//ans数组用来存储当前生成的一个排列
bool hashtable[maxn]={
    
    false};
vector<int>ans;//这里用到vector比使用数组更方便,因为不用关注下标的变化
int n;
void order(int num)//num个位置
{
    
    
    if(num==0){
    
    
            for(int i=0;i<ans.size();i++){
    
    
                printf("%d",ans[i]);
            }
            printf("\n");

        return;
    }
    for(int i=1;i<=n;i++){
    
    
        if(hashtable[i]==false){
    
    
            ans.push_back(i);
            hashtable[i]=true;
            order(num-1);
            ans.pop_back();
            hashtable[i]=false;
        }
    }
}
int main()
{
    
    
    scanf("%d",&n);
    order(n);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45890608/article/details/111225320