我正在尝试创建一种算法,在给它一些随机字母后,例如:abcd,它将显示所有可能的排列,在这种情况下,答案将是:
abcd abc abd acd ab ac ad a bcd bc bd b cd c d
您可以看到,不同的排列必须具有不同的字母,我花了数小时试图做到这一点但没有成功,这是我到目前为止所做的:
vector<char> letters;
letters.push_back('a');
letters.push_back('b');
letters.push_back('c');
letters.push_back('d');
int number_of_letters = 4;
int number_of_repetitions;
vector<char> combination;
vector<char> comb_copy;
for(int i = 0; i < number_of_letters; i++){
number_of_repetitions = 1;
changing_letters = number_of_letters - (i + 1);
for(int j = i+1; j < number_of_letters; j++){
combination.push_back(letters[j]);
}
comb_copy = combination;
for(int i = 0; i < comb_copy.size(); i++){
cout << comb_copy[i];
}
while(number_of_repetitions <= changing_letters){
comb_copy = combinations(comb_copy, number_of_repetitions);
for(int i = 0; i < comb_copy.size(); i++){
cout << comb_copy[i];
}
comb_copy = combination;
number_of_repetitions++;
}
}
vector<char> combinations(vector<char> combi, int reps){
combi.erase(combi.end() - reps);
return (reps > 1?combinations(combi, reps-1):combi);
}
这就是我得到的:
abcd abc abd acd bc bd c
我需要获得:
abcd abc abd acd ab ac ad a bcd bc bd b cd c d
有人可以帮我吗? :)
谢谢!
您希望获得n个项目的所有子集,但空项目除外。有2^n-1
个这样的子集。生成它们的一对方法: