包含重复元素的字符串全排列

思路:编写字符串全排列,首先想到的就是用递归。依次从后面的字符中选择一个不重复的字符替换掉第一个字符,即要注意排除重复选择的情况。然后递归下去,对第二个个位置的字符也采取相同的方法进行替换然后全排列 > > >

至于needSwap为什么是从s [ start ]至s [ end - 1] 元素与s [ end ] 元素比较,而不是直接将s [ start ] 和 s [ end ]进行比较,是因为可能 start ~ end - 1之间有和s [ end ] 相同的元素,即这中间可能有重复元素。我刚开始就是在这里选择了后者,这肯定是不对的,因为我这样的话只有这中间没有重复元素时才能跑对。


#include <bits/stdc++.h>
using namespace std;

bool needSwap(string s, int start, int end) {
	for (int k = start; k < end; ++k)
		if (s[k] == s[end])
			return false;
	return true;
}

void swap(string &s, int i, int j) {
	char tmp = s[i];
	s[i] = s[j];
	s[j] = tmp;
}

void permutation(string s, int start, int length) {
	if (length < 1)
		return;
	if (start < length) {
		for (int i = start; i < length; ++i) {
			if (needSwap(s, start, i)) {
				swap(s, start, i);
				permutation(s, start + 1, length);
				swap(s, start, i);
			}
		}
	} else {
		cout << s << endl;
	}
}

int main() {
    string s;
    while (cin >> s) {
    	permutation(s, 0, s.length());
    }
    return 0;
}

原文地址:https://www.cnblogs.com/deepspace/p/10260716.html