對不起,如果問題不清楚,我想知道如何用C++編寫一個程序,它可以輸出所有句子的組合,使用公式C=n!/(n-k)!
。例如,這是我想已打印的那種東西:如何編寫'n'字符串的所有組合?重複: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...
而且,是有可能有高達1十億組合的或有一些限制?
編輯。
我試過下面的程序,但是我找不到方法來改變上面公式中的「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;
}
'std :: next_permutation' –
只是一個提示:請求「請爲我寫下我的整個程序」並不被看好。 –
好吧,我注意到了。 – user2499266