【问题标题】:cout permutation of three or more string [duplicate]三个或更多字符串的 cout 排列[重复]
【发布时间】:2021-12-13 09:35:38
【问题描述】:

假设我得到了字符串“abc”、“def”和“ghi”,我想生成从这些字符串中挑选出来的所有可能的单词组合。例如 对于“abc”、“def”和“ghi”

我们应该得到

"adg","adh","adi","aeg","aeh","aei","afg","afh","afi", "bdg","bdh","bdi","beg","beh","bei","bfg","bfh","bfi", "cdg","cdh","cdi","ceg","ceh","cei","cfg","cfh","cfi"

怎么做。

我的尝试...

        vector<string> wordset;
        
        for(int i = 0; i < digits.size(); i++ )
        {
            wordset.push_back( latters[digits[i] - '0'] );
        }

                   
        for(int i = 0; i < wordset.size()-2; i++ )
        {
            string word = wordset[i];
            for(int j = 0; j < word.size(); j++ )
            {
                string combn = "";
                combn += word[j];
                                
                for(int k = 0; k < wordset[i+1].size(); k++ )
                {
                    combn += wordset[i+1][k];

                    for(int l = 0; l < wordset[i+2].size(); l++ )
                    {
                        combn += wordset[i+2][l];

                        ans.push_back(combn);
                        combn = "";
                        combn += word[j];
                        combn += wordset[i+1][k];

                    }

                }
            }
        }

【问题讨论】:

标签: c++ string


【解决方案1】:

这是递归允许更简单代码的一个示例:您只需要将第一个单词中的所有字符与其他字符的排列组合起来。

在 C++ 中可能是:

#include <vector>
#include <string>

using std::vector;
using std::string;

// using an array will allow to simply process the end of the array
vector<string> permuts(const string* arr, size_t sz) {
    vector<string> ret;
    switch (sz) {
    case 1:   // one single word: return its individual chars as strings
        for (char c : arr[0]) {
            string str(1, c);
            ret.push_back(str);
        }
    case 0:   // empty array gives an empty vector
        return ret;
    default:
        ;
    }
    // combine chars from first word with permuts of others
    vector<string> tmp = permuts(arr + 1, sz - 1);
    for (char c : arr[0]) {
        for (const string& str : tmp) {
            string str2 = string(1, c) + str;
            ret.push_back(str2);
        }
    }
    return ret;
}

// the version using a vector just delegates to the one using an array
vector<string> permuts(const vector<string>& wordset) {
    return permuts(wordset.data(), wordset.size());
}

【讨论】:

  • permuts 可以重命名为cartesian_product
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 2015-08-14
  • 2015-06-02
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多