抱歉,如果问题不清楚,我想知道如何用 C++ 编写一个程序,使用公式输出一些句子的所有组合C=n!/(n-k)!
。例如,这就是我想要打印的那种东西:
combination no 1: sentence1 sentence2 sentence3 sentence4
combination no 2: sentence1 sentence2 sentence4 sentence3
combination no 3: sentence1 sentence3 sentence2 sentence4
combination no 4: sentence1 sentence3 sentence4 sentence2
combination no 5: sentence1 sentence4 sentence3 sentence2
combination no 6: sentence1 sentence4 sentence2 sentence3
And so on...
另外,是否可以有多达 10 亿个组合,或者有一些限制?
编辑。
我尝试了以下程序,但我找不到改变上面公式中“k”变量的方法。
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
#include <string> // std::string
#include <vector> // std::vector
int main () {
std::string sentence1 = " A Sentence number one ";
std::string sentence2 = " B Sentence number two ";
std::string sentence3 = " C Sentence number three ";
std::string sentence4 = " D Sentence number four ";
// Store all the elements in a container ( here a std::vector)
std::vector<std::string> myVectorOfStrings;
// In the vector we add all the sentences.
// Note : It is possible to do myVectorOfStrings.push_back("Some sentence");
myVectorOfStrings.push_back(sentence1);
myVectorOfStrings.push_back(sentence2);
myVectorOfStrings.push_back(sentence3);
myVectorOfStrings.push_back(sentence4);
// The elements must be sorted to output all the combinations
std::sort (myVectorOfStrings.begin(),myVectorOfStrings.end());
std::cout << "The 4! possible permutations with 4 elements:\n";
do {
//This printing can be improved to handle any number of sentences, not only four.
std::cout << myVectorOfStrings[0] << ' ' << myVectorOfStrings[1] << ' ' << myVectorOfStrings[2] << ' ' << myVectorOfStrings[3] << '\n';
} while ( std::next_permutation(myVectorOfStrings.begin(),myVectorOfStrings.end()) );
std::cout << "After loop: " << myVectorOfStrings[0] << ' ' << myVectorOfStrings[1] << ' ' << myVectorOfStrings[2] << ' ' << myVectorOfStrings[3] << '\n';
return 0;
}