This is a similar problem to ch 8.3.
In recursion, we can think a little bit different: so here are two recursion version:
method 1: perm("abc") can remove "a" and put at the Beginning of perm("bc"), then remove "b" to put at the Beginning of perm("ac")....
method 2: perm("abc") can be divided to perm("bc") then put "a“ in anywhere of ”bc";
//Write a method to compute all permutations of a string
// http://www.chaozh.com/cracking-the-coding-interview-q7-12/
#include
#include
#include
using namespace std;
typedef vector
vs;
// method 1: HAWSTEIN
vs perm(string s){
vs result;
if(s==""){
result.push_back("");
//return result;
}
for(int i =0; i
Also, here is the Java solution: Very short.
public class Permutation {
//https://gist.github.com/xuyirio/3029161
public static void permutateString(String s, String tgs){
int last = tgs.length();
if (last == 0){
System.out.println(s);
return;
}
for (int i = 0; i < last; i++ ){
permutateString(s + tgs.charAt(i), tgs.substring(0, i) + tgs.substring(i+1));
}
}
public static void main(String[] args) {
permutateString("", "112");
}
}
/*
112
121
112
121
211
211
*/