|
| 1 | +package com.eprogrammerz.examples.algorithm.interviewbit; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +import static org.junit.Assert.assertEquals; |
| 9 | + |
| 10 | +/** |
| 11 | + * Given n, 1.. n and k, find permutation of n numbers at kth position |
| 12 | + */ |
| 13 | +public class KthPermutation { |
| 14 | + public String getPermutation(int n, int k) { |
| 15 | + List<Integer> num = new ArrayList<>(); |
| 16 | + for (int i = 1; i <= n; i++) { |
| 17 | + num.add(i); |
| 18 | + } |
| 19 | + List<List<Integer>> per = new ArrayList<>(); |
| 20 | + permutate(num, k, per, new ArrayList<>()); |
| 21 | + List<Integer> p = per.get(per.size() - 1); |
| 22 | + StringBuilder res = new StringBuilder(); |
| 23 | + for (int i : p) { |
| 24 | + res.append(i); |
| 25 | + } |
| 26 | + return res.toString(); |
| 27 | + } |
| 28 | + |
| 29 | + private void permutate(List<Integer> num, int k, List<List<Integer>> per, |
| 30 | + List<Integer> temp) { |
| 31 | + if (per.size() == k) return; |
| 32 | + |
| 33 | + if (num.size() == 0) { |
| 34 | + per.add(new ArrayList<>(temp)); |
| 35 | + } else { |
| 36 | + for (int i = 0; i < num.size(); i++) { |
| 37 | + List<Integer> r1 = num.subList(0, i); |
| 38 | + List<Integer> r2 = num.subList(i + 1, num.size()); |
| 39 | + |
| 40 | + List<Integer> r = new ArrayList<>(); |
| 41 | + r.addAll(r1); |
| 42 | + r.addAll(r2); |
| 43 | + |
| 44 | + temp.add(num.get(i)); |
| 45 | + permutate(r, k, per, temp); |
| 46 | + temp.remove(num.get(i)); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + public void testKthPermutation() { |
| 53 | + String kth = getPermutation(3, 4); |
| 54 | + assertEquals("231", kth); |
| 55 | + } |
| 56 | + |
| 57 | + public String getKthPermutation(int n, int k) { |
| 58 | + List<Integer> num = new ArrayList<>(); |
| 59 | + for (int i = 1; i <= n; i++) { |
| 60 | + num.add(i); |
| 61 | + } |
| 62 | + |
| 63 | + return getKthPermutation(num, k - 1); |
| 64 | + } |
| 65 | + |
| 66 | + private String getKthPermutation(List<Integer> num, int k) { |
| 67 | + int size = num.size(); |
| 68 | + if (size == 0) return ""; |
| 69 | + |
| 70 | + if (k > fact(size)) return ""; |
| 71 | + |
| 72 | + int f = fact(size - 1); |
| 73 | + |
| 74 | + int pos = k / f; |
| 75 | + |
| 76 | + k = k % f; |
| 77 | + |
| 78 | + return String.valueOf(num.remove(pos)) + getKthPermutation(num, k); |
| 79 | + } |
| 80 | + |
| 81 | + private int fact(int n) { |
| 82 | + if (n == 0 || n == 1) return 1; |
| 83 | + return n * fact(n - 1); |
| 84 | + } |
| 85 | + |
| 86 | + @Test |
| 87 | + public void testKthPermutationBetter() { |
| 88 | + String kth = getKthPermutation(3, 4); |
| 89 | + assertEquals("231", kth); |
| 90 | + } |
| 91 | +} |
0 commit comments