【问题标题】:how can print only unique Permutations of a string?如何仅打印字符串的唯一排列?
【发布时间】:2021-05-24 21:37:19
【问题描述】:

此函数打印字符串的排列,如何修改它以使其仅打印唯一的排列? “没有重复”

void RecPermute(string soFar, string rest) {
  if (rest == "")           // No more characters
    cout << soFar << endl;  // Print the word
  else                      // Still more chars
    // For each remaining char
    for (int i = 0; i < rest.length(); i++) {
      string next = soFar + rest[i];  // Glue next char
      string remaining = rest.substr(0, i) + rest.substr(i + 1);
      RecPermute(next, remaining);
    }
}
// "wrapper" function
void ListPermutations(string s) {
  RecPermute("", s);

【问题讨论】:

  • 将排列保存到std::unordered_set,然后打印集合。
  • 代码被错误地重复了两次。代码以包装函数结束

标签: c++ string permutation


【解决方案1】:

您可以使用标准函数 std::next_permutation 创建唯一排列。

例子:

#include <algorithm>
#include <iostream>
#include <string>

void ListPermutations(std::string str) {
    std::sort(str.begin(), str.end()); // sort to start at the first permutation

    do {
        std::cout << str << '\n';

        // get the next unique permutation:
    } while( std::next_permutation(str.begin(), str.end()) );
}

int main() {
    ListPermutations("aaba");
}

输出:

aaab
aaba
abaa
baaa

【讨论】:

    【解决方案2】:

    如果你不允许使用像std::next_permutation这样的库函数,你可以使用回溯和递归来解决这个问题。该算法与具有唯一字符的排列相同,但您需要检查之前是否遇到过该数字。如果以前遇到过字符,请忽略它以避免重复。

    这是带有 cmets 的代码:

    #include <iostream>
    #include <string>
    #include <set>
    
    void printPermutations(std::string &str, int index) {
        if (index == str.size()) {
            std::cout << str << std::endl;
            return;
        }
        std::set<char> soFar;
        // loop from position index onward
        for (auto i = index; i < str.size(); i++) {
            // check we haven't seen character in loop previously
            if (soFar.find(str[i]) == soFar.end()) {
                // store character in set
                soFar.insert(str[i]);
                // swap index with next character in loop
                std::swap(str[index], str[i]);
                printPermutations(str, index + 1);
                // swap back
                std::swap(str[index], str[i]);
            }
        }
    }
    
    // "wrapper" function
    void ListPermutations(std::string s) {
        printPermutations(s, 0);
    }
    
    int main()
    {
        ListPermutations("aaba");
        return 0;
    }
    

    输出:

    aaba
    aaab
    abaa
    baaa
    

    Demo

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多