1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| public class Solution { public String getPermutation(int n, int k) { Set<Integer> set = new HashSet<>(); AtomicInteger atomic = new AtomicInteger(k); StringBuffer sb = new StringBuffer(); for (int i = 1; i <= n; i++) { sb.append(getIndexNum(n, atomic, i, set)); } return sb.toString(); }
public static Integer getIndexNum(int n, AtomicInteger atomic, int index, Set<Integer> set) { int result = 0;
if (index == n) { for (int i = 1; i <= n; i++) { if (!set.contains(i)) { return i; } } }
int fb = fb(n - index);
int i = (atomic.get() - 1) / fb + 1; for (int j = 1; j <= n; j++) { if (!set.contains(j)) { i--; if (i == 0) { result = j; set.add(result); atomic.set(atomic.get() - (((atomic.get() - 1) / fb + 1) - 1) * fb); break; } } } return result; }
public static Integer fb(int k) { if (k == 1) { return 1; } return k * fb(k - 1); }
}
|