题目:一个字符串怎么求出该字符串的全排列
一、实用字典排序 思路很简单:
第一步:从右到左遍历字符串。从字符串的后面开始看有没有相邻的两个数str[i]<str[i+1]的,若有终结循环,进入第二步;没有的话,i--。
第二步:判断i是否小于0;是,则结束;不是;则进入第三。
第三步:从右向左遍历字符串。当str[k]>str[i],进入第四步;否则,k--;
第四步:swap(str[k],str[i])
第五步:反转从第i+1个字符到字符串末尾的字符,reverse(str+i+1,str+num)。
代码如下:
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;
#define MAX 4
bool PrintDictSort(char *str,int N);
int _tmain(int argc, _TCHAR* argv[])
{
int count = 0;
char a[] = "abcd";
while (PrintDictSort(a, MAX))
{
count++;
}
cout << count << endl;
system("pause");
return 0;
}
bool PrintDictSort(char *str, int N)
{
int i;
for (i = N - 2; i >= 0 && str[i] >= str[i + 1]; i--)
{
;
}
if (i < 0)
{
return false;
}
int k;
for (k = N - 1; k > i&&str[k] <= str[i]; k--)
{
;
}
swap(str[i], str[k]);
reverse(str + i + 1, str + N);
cout << str << endl;
}
算法的时间复杂度是O(n!)