github-july-字符串的全排列

来源:互联网 发布:vmware mac os 10.9 编辑:程序博客网 时间:2024/05/22 17:34

题目描述

输入一个字符串,打印出该字符串中字符的所有排列。
例如输入字符串abc,则输出由字符a、b、c 所能排列出来的所有字符

abc、acb、bac、bca、cab 和 cba。


解法1:递归

P(abc) = aP(bc) + bP(ac) + cP(ab) 

void CalcAllPermutation(char* perm, int from, int to){    if (to <= 1)    {        return;    }    if (from == to)    {        for (int i = 0; i <= to; i++)            cout << perm[i];        cout << endl;    }    else    {        for (int j = from; j <= to; j++)        {            swap(perm[j], perm[from]);            CalcAllPermutation(perm, from + 1, to);            swap(perm[j], perm[from]);        }    }}




解法2:字典序【??】

0 0
原创粉丝点击