How can I get all the anagrams of a string

雨燕双飞 提交于 2019-12-11 05:25:42

问题


Im trying to find all the possible anagrams of a string and store them in an array using only recursion.

Im stuck and this is all i have.

int main()
{
    const int MAX = 10;
    string a = "ABCD";
    string arr[10];

    permute(arr, a, 0, a.size(), 0);

    return 0;
}

void permute(string arr[], string wrd, int firstLetter, int lastLetter, int it)
{
    if (firstLetter == lastLetter)
        *arr = wrd;
    else
    {
            swap(wrd[firstLetter], wrd[it]);
            permute(arr, wrd, firstLetter + 1, lastLetter, it++);
    }
}

The order doesnt matter. Ex: string "abc"; array should have: abc, acb, bca, bac, cab, cba

Edit: im trying to find all permutations of a word and insert them into an array without using loops.


回答1:


You should use string& for the parameter as it will be more efficient. You should iterate through chars.

#include <iostream>
#include <string>
using namespace std;

void permute(string* arr, int& ind, string& wrd, int it) {
    if (it == wrd.length()) {
        arr[ind++] = wrd;
    } else {
        for (int i = it; i < wrd.length(); ++i) {
            swap(wrd[i], wrd[it]);
            permute(arr, ind, wrd, it + 1);
            swap(wrd[i], wrd[it]);
        }
    }
}

int main() {
    string a = "ABCD";
    string arr[100]; // enough size to store all permutations
    int ind = 0;
    permute(arr,ind, a, 0);
    for (int i = 0; i < ind; ++i) {
        cout << arr[i] << endl;
    }
    return 0;
}



回答2:


You need to store the current value before permute() calls permute() again. This is where you are losing some of your values.




回答3:


The easiest way to do this would be something like this:

// Precondition locs size is the same x length and arr is the right size to handle all the permutations
void permute(string arr[], string x, int locs[], int size, int & index)
{
    for(int i = 0; i<size; i++)
    {
        if(locs[i] < size) locs[i]++;
        else locs[i] = 0;
    }
    arr[index] = "";
    for(int i = 0; i<size; i++)
    {
        arr[index] += x[locs[i]];
    }
    index++;
}

Hope this really helps.



来源:https://stackoverflow.com/questions/47623079/how-can-i-get-all-the-anagrams-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!