1
dreampuf 2011-10-25 01:57:23 +08:00
单字符数组的笛卡尔积.
strs = "abc" strs_args = strs * len(strs) for i in itertools.product(*strs_args): print "".join(i) |
2
qiao 2011-10-25 02:34:47 +08:00
好久没写 C++ 了:
<pre> #include <iostream> #include <string> #include <algorithm> using namespace std; template <typename T> void permutation(T t, void (*fn)(const T &)) { sort(t.begin(), t.end()); do { fn(t); } while(next_permutation(t.begin(), t.end())); } void print(const string &s) { cout << s << endl; } int main() { string s("baa"); permutation(s, print); return 0; } </pre> |
4
qiao 2011-10-25 21:24:16 +08:00
@tsuibin
每次记录一下被交换的元素即可: #include <iostream> #include <string> #include <algorithm> using namespace std; void permutation_helper(string &str, int start, int end) { if (start == end) { cout << str << endl; } else { bool visited[256]; fill(visited, visited + 256, false); for (int i = start; i <= end; ++i) { if (!visited[str[i]]) { swap(str[start], str[i]); permutation_helper(str, start + 1, end); swap(str[start], str[i]); visited[str[i]] = true; } } } } void permutation(string str) { sort(str.begin(), str.end()); permutation_helper(str, 0, str.length() - 1); } int main() { string s("aab"); permutation(s); return 0; } |
5
tsuibin OP |