Thursday, June 12, 2014

LeetCode PermutationSequence

This problem is similar to number to Integer to Roman

Here we need to be careful about the k.
"k--" makes sure the k is not exactly the time of (n-1)!
for example n = 4, k=6. The start digit should be 1, instead of 2.

public String getPermutation(int n, int k) {
String res = "";
k--;
ArrayList<Integer> array = new ArrayList<Integer>();
for (int i=1; i<=n; i++) array.add(i);
while (n>0) {
res += array.get(k/fact(n-1));
array.remove(array.get(k/fact(n-1)));
k = k%fact(n-1);
n--;
}
return res;
}

public int fact(int i) {
int res = 1;
while (i > 1) {
res *= i;
i--;
}
return res;
}

No comments:

Post a Comment