递归方法应该没问题:
If the list is empty
Return the only possible permutation, an empty list.
Else
For each element of the list
Put the element at the first place (i.e. swap it with the first element)
(If the element is same as the first one, don't swap)
Recursively find all the permutations of the rest of the list
此算法不会产生重复排列。
这是一个python实现:
def permute(s):
if len(s) == 0:
return [[]]
ret = [s[0:1] + x for x in permute(s[1:])]
for i in range(1, len(s)):
if s[i] == s[0]:
continue
s[0], s[i] = s[i], s[0]
ret += [s[0:1] + x for x in permute(s[1:])]
return ret
s = [0, 1, 2, 3]
for x in permute(s):
print x
C中类似的东西应该是这样的:
void swap(char* str, int i, int j)
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
void permute(char *string, int start, int end)
{
if(start == end)
{
printf("%s\n", string);
return;
}
permute(string, start + 1, end);
int i;
for(i = start + 1; i < end; i++)
{
if(string[start] == string[i])
continue;
swap(string, start, i);
permute(string, start + 1, end);
swap(string, start, i);
}
}