0

I am given a string and i need to find all possible letter combinations of this string. What is the best way I can achieve this? example:

abc

result:

abc
acb
bca
bac
cab
cba

i have nothing so far. i am not asking for code. i am just asking for the best way to do it? an algorithm? a pseudocode? maybe a discussion?

K Mehta
  • 10,083
  • 4
  • 43
  • 73
lin
  • 163
  • 1
  • 2
  • 6

5 Answers5

3

you can sort it then use std::next_permutation

take a look at the example: http://www.cplusplus.com/reference/algorithm/next_permutation/

Hayri Uğur Koltuk
  • 2,890
  • 3
  • 29
  • 60
1

Do you want combinations or permutations? For example, if your string is "abbc" do you want to see "bbac" once or twice?

If you actually want permutations you can use std::next_permutation and it'll take care of all the work for you.

Mark B
  • 93,381
  • 10
  • 105
  • 184
1

If you want the combinations (order independant) You can use a combination finding algorithm such as that found either here or here. Alternatively, you can use this (a java implementation of a combination generator, with an example demonstrating what you want.

Alternatively, if you want what you have listed in your post (the permutations), then you can (for C++) use std::next_permutation found in <algorithm.h>. You can find more information on std::next_permutation here.

Hope this helps. :)

Community
  • 1
  • 1
Thomas Russell
  • 5,630
  • 3
  • 30
  • 64
0

In C++, std::next_permutation:

std::string s = "abc";
do
{
  std::cout << s << std::endl;
} while (std::next_permutation(s.begin(), s.end()));
Peter Alexander
  • 51,762
  • 11
  • 116
  • 167
0

Copied from an old Wikipedia article;

For every number k, with 0 ≤ k < n!, the following algorithm generates a unique permutation on sequence s.

function permutation(k, s) {
     for j = 2 to length(s) {
        swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
        k := k / j;        // integer division cuts off the remainder
     }
     return s;
}
Qwerky
  • 17,904
  • 6
  • 46
  • 78