求全排列的4种情况

四种情况:
1. 给定字符串,无重复
2. 给定字符串,有重复
3. 给定数字n,求1-n的所有全排列
4. 使用STL函数自带求下一个全排列函数

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;


// 字符串全排列,无重复
void perm1(char* A, int cur)
{
    if(cur == strlen(A)-1)
    {
        cout<<A<<endl;
        return;
    }

    char temp;
    for(int i=cur; i<strlen(A); i++)
    {
        temp = A[i];
        A[i] = A[cur];
        A[cur] = temp;

        perm1(A,cur+1);

        temp = A[i];
        A[i] = A[cur];
        A[cur] = temp;
    }
}

// 字符串全排列,可重复
void perm2(char* A, int cur)
{
    if(cur == strlen(A)-1)
    {
        cout<<A<<endl;
        return;
    }

    char temp;
    for(int i=cur; i<strlen(A); i++)
    {
        int isSwap = true;
        for(int j=i; j>cur; j--){
            if(A[cur] == A[j]){
                isSwap = false;
            }
        }
        if(isSwap)
        {
            temp = A[i];
            A[i] = A[cur];
            A[cur] = temp;

            perm2(A,cur+1);

            temp = A[i];
            A[i] = A[cur];
            A[cur] = temp;

        }

    }
}

// 求1-n的全排列,无重复
void perm3(int n, int* A, int cur){
    int i,j;
    if(cur == n){
        for(int i=0; i<n; i++){
            printf("%d",A[i]);
        }
        printf("\n");
        return ;
    }

    for(int i=1; i<=n; i++){
        bool ok = true;
        for(int j=0; j<cur; j++){
            if(A[j] == i) ok = false;
        }
        if(ok){
            A[cur] = i;
            perm3(n,A,cur+1);
        }
    }
}

// 求字符串全排列,可重复,std自带
void perm4(int n, int *A){
    sort(A,A+n);
    do{
        for(int i=0; i<n ; i++) cout<<A[i]<<" ";
        cout<<endl;
    }while(next_permutation(A,A+n));
}

int main()
{
    int A[10] = {1,2,1};
    perm4(3,A);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值