How do I get all the combinations of characters.

Say I have a string, how do I generate all the combinations of its characters?
example: I have a string "Tea",how do I get:"tea","tae","ate","eta","eat","aet"
try this :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}


void permute(char *a, int i, int n)
{
    int j;
    if (i == n)
        std::cout << string(a);
    else
    {
        for (j = i; j <= n; j++)
        {
            swap((a + i), (a + j));
            permute(a, i + 1, n);
            swap((a + i), (a + j)); //backtrack
        }
    }
}

int main()
{
    char a[] = "BAC";
    int len = sizeof(a) / sizeof(a[0]);
    permute(a, 0, len);
    getchar();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <algorithm>

void print_permutations(std::string str)
{
    std::sort(str.begin(), str.end());
    do {
        std::cout << str << '\n';
    //http://en.cppreference.com/w/cpp/algorithm/next_permutation
    } while(std::next_permutation(str.begin(), str.end()));
}

int main()
{
    print_permutations("tea");           
}
aet
ate
eat
eta
tae
tea
http://coliru.stacked-crooked.com/a/55980090ef2f73c5
@MiiNiPaa nice :)
@Ericool you do not need to implement your own swap function (and it is not recomended to do it in global namespace. At least name it differently). Just use iter_swap: http://en.cppreference.com/w/cpp/algorithm/iter_swap
I just copy paste from another thread . Normaly I use std::swap .
Topic archived. No new replies allowed.