package com.anuragkapur.misc;

/**
 * Print all permutations of a given string. 
 * Note: substrings are not permutations
 * 
 * @author anurag.kapur
 */
public class StringPermute {

	public static int count = 0;
	
	public static void permute(String soFar, String strLeft) {
		
		if(strLeft.length() == 1) {
			soFar += strLeft;
			System.out.println(++count + " :: " + soFar);
		}
		
		for(int i=0; i<strLeft.length(); i++) {
			permute(soFar + strLeft.charAt(i), strLeft.substring(0,i) + strLeft.substring(i+1));
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String input = "abcd";
		permute("",input);
	}
}
@@ -375,20 +375,23 @@
 ar);%0A%09%09%7D
+else%7B
 %0A%09
-%09%0A
 %09%09for(in
@@ -424,16 +424,17 @@
  i++) %7B%0A
+%09
 %09%09%09permu
@@ -513,16 +513,21 @@
 (i+1));%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%09

Optimised no. of recursive calls by preventing calls when unprocessed string is of 0 length