|
| 1 | +package com.kunal.strings; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | + |
| 5 | +public class Permutations { |
| 6 | + public static void main(String[] args) { |
| 7 | +// permutations("", "abc"); |
| 8 | + |
| 9 | +// ArrayList<String> ans = permutationsList("", "abc"); |
| 10 | +// System.out.println(ans); |
| 11 | + |
| 12 | + System.out.println(permutationsCount("", "abcd")); |
| 13 | + } |
| 14 | + |
| 15 | + static void permutations(String p, String up) { |
| 16 | + if (up.isEmpty()) { |
| 17 | + System.out.println(p); |
| 18 | + return; |
| 19 | + } |
| 20 | + char ch = up.charAt(0); |
| 21 | + for (int i = 0; i <= p.length(); i++) { |
| 22 | + String f = p.substring(0, i); |
| 23 | + String s = p.substring(i, p.length()); |
| 24 | + permutations(f + ch + s, up.substring(1)); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + static ArrayList<String> permutationsList(String p, String up) { |
| 29 | + if (up.isEmpty()) { |
| 30 | + ArrayList<String> list = new ArrayList<>(); |
| 31 | + list.add(p); |
| 32 | + return list; |
| 33 | + } |
| 34 | + char ch = up.charAt(0); |
| 35 | + |
| 36 | + // local to this call |
| 37 | + ArrayList<String> ans = new ArrayList<>(); |
| 38 | + |
| 39 | + for (int i = 0; i <= p.length(); i++) { |
| 40 | + String f = p.substring(0, i); |
| 41 | + String s = p.substring(i, p.length()); |
| 42 | + ans.addAll(permutationsList(f + ch + s, up.substring(1))); |
| 43 | + } |
| 44 | + return ans; |
| 45 | + } |
| 46 | + |
| 47 | + static int permutationsCount(String p, String up) { |
| 48 | + if (up.isEmpty()) { |
| 49 | + return 1; |
| 50 | + } |
| 51 | + int count = 0; |
| 52 | + char ch = up.charAt(0); |
| 53 | + for (int i = 0; i <= p.length(); i++) { |
| 54 | + String f = p.substring(0, i); |
| 55 | + String s = p.substring(i, p.length()); |
| 56 | + count = count + permutationsCount(f + ch + s, up.substring(1)); |
| 57 | + } |
| 58 | + return count; |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments