5. 字符串的全排列
来源:互联网 发布:安卓游戏编程 编辑:程序博客网 时间:2024/05/23 19:16
实现一个函数,打印出一个字符串中字符的所有可能顺序。换言之,就是打印出原来字符串中所有字符的全排列。例如,对于字符串“hat”,函数应该打印出字符串“tha”,“aht”,“tah”,“ath”,“hta”,“hat”。将输入字符串中的每个字符作为一个独立的字符,即使它们发生重复。对于字符串“aaa”,函数应该打印出6个“aaa”。可以按任何顺序打印出全排列。
程序的代码如下:
#include "stdafx.h"
#include <iostream.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void DoPermute(char in[], char out[], int used[], int length, int recurslev)
{
int i;
// Base case
if(recurslev == length)
{
printf("%s/n", out); // Print permutation
return;
}
// Recursive case
for(i = 0; i < length; i++)
{
if(used[i]) // if used, skip to next letter
continue;
out[recurslev] = in[i]; // Put current letter in output
used[i] = 1;
DoPermute(in, out, used, length, recurslev + 1);
used[i] = 0;
}
}
int Permute(char inString[])
{
int length, i, *used;
char *out;
length = strlen(inString);
out = (char*)malloc(length + 1);
if(!out) // Failed
return 0;
// So printf doesn't run past the end of the buffer
out[length] = '/0';
used = (int*)malloc(sizeof(int) * length);
if(!used) // Failed
return 0;
// Start with no letters used, so zero array
for(i = 0; i < length; i++)
{
used[i] = 0;
}
DoPermute(inString, out, used, length, 0);
free(out);
free(used);
return 1; // Success
}
int main()
{
char str[] = "hat";
Permute(str);
return 0;
}
// 程序的执行结果如下:
- 5. 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- 字符串的全排列
- jquery 坦克大战
- 如何在spring框架中解决多数据源的问题
- trace帮助隐藏错误
- SQL字符串处理函数汇总
- java操作word、execl总结
- 5. 字符串的全排列
- Lucene入门项目实例---比较Lucene方式搜索与传统String方式搜索的效率
- Java实现利用搜索引擎收集网址的程序
- c++图书管理系统
- Kill杀死进程方法大全
- HTA
- 很不错的,VC 多线程编程
- ext编写自定义组件
- 访问需要HTTP Basic Authentication认证的资源的各种语言的实现