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