【问题标题】:All the possible combinations of 'n' strings, with repetitions: C= n!/(n-k)! [duplicate]'n' 个字符串的所有可能组合,重复:C= n!/(n-k)! [复制]
【发布时间】:2013-06-20 02:32:20
【问题描述】:

我正在尝试这样的事情:

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

等等……

现在,使用以下代码,我如何处理公式中的“k”变量? 有什么遗漏吗?同样,它是关于重复的组合,所以我认为公式是 C= n!/(n-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;
}

【问题讨论】:

  • 我知道,你可能是对的。我试图阅读它,但事实是它对我来说仍然太难了。所以我希望以一种更简单的方式来处理这个问题。

标签: c++ string combinations


【解决方案1】:

您所说的k 是自动处理的。假设,如果您将两个相似的句子插入向量中,假设有 4 个句子,其中两个是相同的。那么排列的总数是4!/2!=12。因此,该函数仅打印 12 个排列(不是24)。用类似的句子查看你修改代码的输出here:

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 2011-11-10
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2018-09-02
    相关资源
    最近更新 更多