C++ 实现字典排序以查找唯一排列
我试图实现一种算法,以生成所描述的字典顺序的唯一排列。下面是我的实现C++ 实现字典排序以查找唯一排列,c++,permutation,C++,Permutation,我试图实现一种算法,以生成所描述的字典顺序的唯一排列。下面是我的实现 void My_Permute(string word) { sort(word.begin(),word.end()); int size = word.size(); while (true) { cout << word << endl; int i = size - 2; for (; i >= 0; --i)
void My_Permute(string word) {
sort(word.begin(),word.end());
int size = word.size();
while (true) {
cout << word << endl;
int i = size - 2;
for (; i >= 0; --i) {
if (word[i] < word[i+1]) break;
}
if (i <= -1) break;
swap(word[i],word[i+1]);
cout << word << endl;
reverse(word.begin()+i+1,word.end());
}
}
链接算法缺少第2步
void Permute(string word) {
sort(word.begin(), word.end());
int size = word.size();
while (true) {
cout << word << endl;
// Find the largest index k such that a[k] < a[k + 1].
// If no such index exists, the permutation is the last permutation.
int i = size - 2;
for (; i >= 0; --i) {
if (word[i] < word[i+1])
break;
}
if (i < 0)
break;
// Find the largest index l such that a[k] < a[l].
// Since k + 1 is such an index, l is well defined and satisfies k < l.
int j = size - 1;
for (; ; --j) {
if (word[i] < word[j])
break;
}
// Swap a[k] with a[l].
swap(word[i], word[j]);
// Reverse the sequence from a[k + 1] up to and including the
// final element a[n].
reverse(word.begin() + i + 1, word.end());
}
}
24(即4!)行,如预期
顺便说一句,你应该尽可能多地使用它。风格改进建议:不要使用
if(讽刺的是,你在解决方案中使用使用namespace std
it;)@理想化只是为了避免重新格式化代码的复杂性,这样版本之间的差异就会更清楚:但是我在没有itI的情况下测试了它,就像你使用的网站一样。谢谢你的知识。
void Permute(string word) {
sort(word.begin(), word.end());
int size = word.size();
while (true) {
cout << word << endl;
// Find the largest index k such that a[k] < a[k + 1].
// If no such index exists, the permutation is the last permutation.
int i = size - 2;
for (; i >= 0; --i) {
if (word[i] < word[i+1])
break;
}
if (i < 0)
break;
// Find the largest index l such that a[k] < a[l].
// Since k + 1 is such an index, l is well defined and satisfies k < l.
int j = size - 1;
for (; ; --j) {
if (word[i] < word[j])
break;
}
// Swap a[k] with a[l].
swap(word[i], word[j]);
// Reverse the sequence from a[k + 1] up to and including the
// final element a[n].
reverse(word.begin() + i + 1, word.end());
}
}
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba