用于移除符号和生成排列的算法

时间:2018-06-16 18:05:40

标签: c++ arrays algorithm

我有以下字符数组" AbA"我想生成一组char数组,它代表删除char =' A'的所有可能组合。从最初的char数组开始,结果将是一个包含" bA"," Ab"," b"另一个例子是" AbAbA"然后结果将是" bAbA" " ABBA" " ABAB"" BBA"等等最后一个元素将是bb(没有3 A' s)。如何创建这样的算法,应该是什么想法?

1 个答案:

答案 0 :(得分:0)

您可以使用回溯算法并使用for循环删除原始字符串中模式字符的每个外观,并检查之前是否创建了找到的字符串,如果没有打印它并在字符串上运行回溯算法找不到它的字符。

#include <iostream>
#include <string>
#include <set>

using namespace std;

set <string> combinations;

inline void back_track_character_remover (string orig, char pat){

    for (int i=0 ; i<orig.size()-1 ; i++){
        if (orig[i]==pat){ // find each appearance of pattern on original string
            int t = combinations.size();
            string new_orig = orig.substr(0,i)+orig.substr(i+1,orig.size()-i-1); // create new string with the found pattern omitted
            combinations.insert(new_orig);
            if (combinations.size()!=t){ // check if adding the new string makes a new permutation
                cout << new_orig << endl; // print new combination 
                back_track_character_remover(new_orig,pat); // checl new string to find other appearances of pattern
            }
        }
    }
    // for easier use of for loop check last element separately
    int t = combinations.size();
    if (orig[orig.size()-1]==pat){
        string new_orig = orig.substr(0,orig.size()-1);
        combinations.insert(new_orig);
        if (combinations.size()!=t){
            cout << new_orig << endl;
            back_track_character_remover(new_orig,pat);
        }
    }
}

int main(){

    string original;
    char pattern;
    cin >> original >> pattern;
    combinations.empty();
    cout << original << endl;
    back_track_character_remover(original,pattern);

}