permutation algorithm 40 points

2007-02-11 9:32 pm
Can someone please write the follow function:

void permutateString(string s)
{
}

which permutate all characters in a string and output all permutations:
example
input: abc

output:
abc
acb
bac
bca
cab
cba

input: abcd
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
....
....

回答 (2)

2007-02-11 10:30 pm
✔ 最佳答案
namespace ConsoleApplication3

{

class Permute

{

private void swap (ref char a, ref char b)

{

if(a==b)return;

a^=b;

b^=a;

a^=b;

}

public void setper(char[] list)

{

int x=list.Length-1;

go(list,0,x);

}

private void go (char[] list, int k, int m)

{

int i;

if (k == m)

{

Console.Write (list);

Console.WriteLine (" ");

}

else

for (i = k; i <= m; i++)

{

swap (ref list[k],ref list[i]);

go (list, k+1, m);

swap (ref list[k],ref list[i]);

}

}

}

class Class1

{

static void Main()

{

Permute p = new Permute();

string c="sagiv";

char []c2=c.ToCharArray ();

/*calling the permute*/

p.setper(c2);

}

}

}
2007-02-12 7:39 am
if you use C++, I have a trick for you:
#include
using namespace std;
...
next_permutation(iterator begin, iterator end);
...
Then the remaining job is sort the string first, and then call next_permutation() :

sort(s.begin(), s.end());
while (next_permutation(s.begin(),s.end()) cout << s;

But if you use C, no way to help but by coding your own.

2007-02-11 23:41:32 補充:
更正:#include 「少於」algorithm「大於」看來「Yahoo!知識 」還有一些小蟲(Bug)存在.....


收錄日期: 2021-04-12 23:19:42
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070211000051KK01805

檢視 Wayback Machine 備份