char * full_string; // String is defined... hopefully you get this
void permute(char * str, int length) {
if(length == 0) { // if the length to permute is 0, string should be as-is. This is the base case of the recursion.
printf(“%s\n”, full_string);
return;
} else { // Otherwise... (Recursive case)
for(int i = 0; i < length; ++i) {
swap(str[0], str[i]); // Swap the first character with the i-th character
permute(str+1, length-1); // Get all permutations with the i-th character as the first character
swap(str[0], str[i]); // Get the original string back for the next loop
}
}
}
要理解的最难的部分是递归位。试着用一个简单的例子来描述它是如何工作的,你应该看看它是如何工作的。
本质上是一个字符串'abc'
找到的a + permutations('bc')
的情况下,这打破了寻找ab + permutations('c')
和'ac' + permutations('b')
,这你想要的所有排列'a' + permutations('bc')
,'b' + permutations('ac')
,并且'c' + permutations('ab')
所有排列然后(例如)下一个递归调用只会让你'abc'
和'acb'
。
然后在'b'
是您的第一个字符并且'c'
是您的第一个字符的情况下完成相同的过程。
希望你可以看到这个同样的过程如何打破一个更大的串入找到的第一个字符的排列+剩余的字符的所有排列
感谢justmscs ..这是你第三次帮助我。 :)看起来像我们两个正在准备接受采访:ms后面的采访:P ...我们能成为朋友吗 ?因为这样我们可以更积极地互相帮助:) – Shauny 2014-12-19 09:04:43
并且您对此的时间复杂性有任何想法。 – Shauny 2014-12-19 09:14:52
很高兴。 SO是一个很棒的地方,我在这里学到了很多东西。由于长度为n的字符串具有n!个排列(如果字符是唯一的),因此其复杂度为'n!'。 – justmscs 2014-12-19 09:21:13