|
| 1 | +import java.util.ArrayList; |
| 2 | + |
| 3 | +public class CombinationPermutation { |
| 4 | + public static void main(String[] args) { |
| 5 | + |
| 6 | + String s = "abcd"; |
| 7 | + int k = 2; |
| 8 | + System.out.println("Combination"); |
| 9 | + combinationK("", s, k); |
| 10 | + System.out.println("Permutation"); |
| 11 | + permutationK(s.toCharArray(), s.length(), k); |
| 12 | + System.out.println("MoveInOut"); |
| 13 | + move(s.toCharArray(), s.length(), new ArrayList<String>(), true); |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | + public static void combinationK(String prefix, String s, int K) { |
| 18 | + if (K == 0) { |
| 19 | + System.out.println(prefix); |
| 20 | + return; |
| 21 | + } |
| 22 | + for (int i = 0; i < s.length(); ++i) |
| 23 | + combinationK(prefix + s.charAt(i), s.substring(i + 1), K - 1); |
| 24 | + } |
| 25 | + |
| 26 | + public static void permutationK(char[] s, int n, int K) { |
| 27 | + if (K == 0) { |
| 28 | + for (int i = n; i < s.length; ++i) |
| 29 | + System.out.print(s[i]); |
| 30 | + System.out.println(); |
| 31 | + return; |
| 32 | + } |
| 33 | + for (int i = 0; i < n; ++i) { |
| 34 | + swap(s, i, n - 1); |
| 35 | + permutationK(s, n - 1, K - 1); |
| 36 | + swap(s, i, n - 1); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static void swap(char[] a, int left, int right) { |
| 41 | + char tmp = a[left]; |
| 42 | + a[left] = a[right]; |
| 43 | + a[right] = tmp; |
| 44 | + } |
| 45 | + |
| 46 | + public static void move(char[] s, int n, ArrayList<String> result, boolean pick) { |
| 47 | + if (n == 0) { |
| 48 | + System.out.println(result.toString()); |
| 49 | + return; |
| 50 | + } |
| 51 | + move(s, n - 1, result, true); |
| 52 | + if (pick) { |
| 53 | + result.add(String.valueOf(s[n - 1])); |
| 54 | + } else { |
| 55 | + result.remove(String.valueOf(s[n - 1])); |
| 56 | + } |
| 57 | + move(s, n - 1, result, false); |
| 58 | + |
| 59 | + } |
| 60 | +} |
0 commit comments