算法练习-字符串全排列

练习问题来源

https://wizardforcel.gitbooks.io/the-art-of-programming-by-july/content/01.06.html

要求

输入一个字符串,打印出该字符串中字符的所有排列。

例如输入字符串abc,则输出由字符a、b、c 所能排列出来的所有字符串:
abc、acb、bac、bca、cab 和 cba。

解法

输出全排列一般采用递归的方式,对集合中的元素依次选择一个作为首个元素,全排列其他的元素,在固定首个元素后的下一轮全排列中继续选择一个元素作为首个元素,以此方式递归地实现排列直至到两个元素的全排列,就成了两元素交换。

例如对 abcd 全排列,依次将 a, b, c, d 作为固定的首个元素,再排列剩下三个元素的全排列 a-bcd b-acd c-bad d-bca

// -----------------------------------------------------------------------
// Output full permutation.
// Referred to: http://blog.csdn.net/prstaxy/article/details/
// Use recursive algorithm to achieve this requirement.
// 2016/5/26

void SwapStr(char cStr[], int m, int n){
    char cTemp = cStr[m];
    cStr[m] = cStr[n];
    cStr[n] = cTemp;
}
void Permutation(char cStr[], int m, int n){
    if(m ==n)
    {
        for(int i=0; i<=n; i++)
            cout << cStr[i] << " ";
        cout <<endl;
    }
    else
    {
        for(int i=m; i<=n; i++)
        {
            SwapStr(cStr, i, m);
            Permutation(cStr, m+1, n);
            SwapStr(cStr, i, m);
        }
    }
}
int OutPermu1()  
{  
    char a[]= "1234";// {'1', '2', '3', '4', '5', '6', '7', '8'};  
    Permutation(a,0,3);
    return 0;  
}
// Use STL's function: next_permutation().
int OutPermu2()  
{  
    int a[] = {1,2,3};

    do  
    {  
        cout << a[0] << " " << a[1] << " " << a[2] << endl;  
    }  
    while (next_permutation(a,a+3));//求下一个排列数 #include<algorithm>  
    //while (prev_permutation(a,a+3));//求上一个排列数,初始数组用逆序来调用可以输出全排列  
    return 0;
}

void main()
{
    OutPermu1();
}

转载于:https://www.cnblogs.com/nobodyzhou/p/5530686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值