Solution: For strings without duplicate characters, the solution is not difficult. To avoid duplication, definitely you can use a hashtable to memorize the permutations that you had outputted. Considering that hashtable may cost a lot of space, some other solutions are desired. However, many solutions on the web actually are incorrect. Here gives a correct solution by using a bit vector (or counting array).
- The key thing is that if now I am gonna swap a character c to position i, I must guarantee previously there is no c that has been swapped to position i. This is the important constraint to avoid duplicate.
- Then we can use an array to track this. If the string only contains characters that range from 'a' to 'z', then we only need an array of the length 26. The code is as follow:
void permutation(string &s, int idx) { if(idx == s.size()) { cout << s << endl; return; } char a[26] = {0}; for(int i = idx; i < s.size(); i++) { if(a[s[i] - 'a'] == 1) continue; a[s[i] - 'a'] = 1; swap(s[idx], s[i]); permutation(s, idx+1); swap(s[idx], s[i]); } }
Permutations definition
ReplyDeleteWhat is a permutation? , define Permutation, why we use permutation?
http://www.infoaw.com/article.php?articleId=945