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,323
  • 4
  • 46
  • 76
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,970
  • 4
  • 31
  • 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
  • 95,107
  • 10
  • 109
  • 188
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,870
  • 4
  • 33
  • 68
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
  • 53,344
  • 14
  • 119
  • 168
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
  • 18,217
  • 6
  • 44
  • 80