Skip to content

Instantly share code, notes, and snippets.

@hfknight
Created September 15, 2014 04:20
Show Gist options
  • Save hfknight/4b04cb0c70a6a62e7b10 to your computer and use it in GitHub Desktop.
Save hfknight/4b04cb0c70a6a62e7b10 to your computer and use it in GitHub Desktop.
leetcode - permutation sequence
public String getPermutation(int n, int k) {
if (n <= 0 || k <= 0)
return "";
// can't use array because we need remove item each time
// create the number array
int mod = 1;
ArrayList<Integer> nl = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
nl.add(i);
mod *= i; // calculate n!
}
k--; // 0-based
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
mod /= (n - i); //start from (n-1)!
int idx = k / mod; // the root of subtree
k %= mod;
sb.append(nl.get(idx));
nl.remove(idx);
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment