[1,2,3,…,n] contains a total of n! unique permutations.By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123""132""213""231""312""321"
Note: Given n will be between 1 and 9 inclusive.
Solution:
public class Solution {
public String getPermutation(int n, int k) {
ArrayList<Integer> numberPermutations = new ArrayList<Integer>();
int count = 1;
numberPermutations.add(1);
for(int i=1; i<n; i++)
{
count*=i;
numberPermutations.add(count);
}
StringBuilder solution = new StringBuilder();
ArrayList<Integer> used = new ArrayList<Integer>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i=0; i<n; i++)
{
numbers.add(i+1);
}
count=k-1;
for(int i=0; i<n; i++)
{
int position = count / numberPermutations.get(n-i-1);
count -= (position * numberPermutations.get(n-i-1));
solution.append(numbers.get(position));
numbers.remove(position);
}
return solution.toString();
}
}
No comments :
Post a Comment