C++ 中列表中的缺失排列


問題陳述

給定任何單詞的排列列表。從排列列表中找出缺失的排列。

示例

If permutation is = { “ABC”, “ACB”, “BAC”, “BCA”} then missing
permutations are {“CBA” and “CAB”}

演算法

  • 建立所有給定字串的集合
  • 以及所有排列的另一個集合
  • 返回兩個集合之間的差異

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
void findMissingPermutation(string givenPermutation[], size_t
permutationSize) {
   vector<string> permutations;
   string input = givenPermutation[0];
   permutations.push_back(input);
   while (true) {
      string p = permutations.back();
      next_permutation(p.begin(), p.end());
      if (p == permutations.front())
         break;
      permutations.push_back(p);
   }
   vector<string> missing;
   set<string> givenPermutations(givenPermutation,
   givenPermutation + permutationSize);
   set_difference(permutations.begin(), permutations.end(),
      givenPermutations.begin(),
      givenPermutations.end(),
      back_inserter(missing));
   cout << "Missing permutations are" << endl;
   for (auto i = missing.begin(); i != missing.end(); ++i)
      cout << *i << endl;
}
int main() {
   string givenPermutation[] = {"ABC", "ACB", "BAC", "BCA"};
   size_t permutationSize = sizeof(givenPermutation) / sizeof(*givenPermutation);
   findMissingPermutation(givenPermutation, permutationSize);
   return 0;
}

在編譯和執行以上程式時。它生成以下輸出 −

輸出

Missing permutations are
CAB
CBA

更新於: 20-12-2019

76 次瀏覽

開啟您的 職業生涯

完成課程認證

開始學習
廣告
© . All rights reserved.