Print All String Combinations Using Recursive function Print All String Combinations Using Recursive function

Print all the possible combinations of a given String using Recursive function in Java

Here we’re using two recursive functions given the string is “abcd”:

  1. substring is responsible for generating all possible substrings of given string in forward direction i.e. a, ab, abc, abcd, b, bc, bcd, c, cd, and d
  2. permutation is responsible for generating all possible permutation of substring generated by substring() method of same length for e.g. possible permutation of abc is abc, acb, bac, bca, cab, and cba
public class PrintAllCombinationOfString {

	public static void main(String[] args) {
		String s = "abcd";
		for (int i = 0; i < s.length(); i++) {
			substring(s, "", i);
		}
	}
	
	public static void substring(String content, String part, int index) {
		if (index >= content.length()) {
			return;
		}
		String sub = part + content.charAt(index);

		permutation("", sub);

		substring(content, sub, index + 1);
	}

	private static void permutation(String prefix, String str) {
		int n = str.length();
		if (n == 0) {
			System.out.println(prefix);
		} else {
			for (int i = 0; i < n; i++) {
				permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
			}
		}
	}
}
Output
a ab ba abc acb bac bca cab cba abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba b bc cb bcd bdc cbd cdb dbc dcb c cd dc d