The set [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"Given n and k, return the kth permutation sequence. (Note: Given n will be between 1 and 9 inclusive.)
The best way to approach the problem is to divide and conquer:
let's start with numbers 1, 2, 3, 4, and we can divide the sequences into 4 groups each starts with 1, 2, 3, 4, the number of sequences in each are 3!, k/3! will decide which group the kth sequence belongs to, saying k=9, k/3! = 1, so kth sequence belongs with group starts with 2.
now we have 1,3,4 and we should look for k%3!=9%6=3th sequence in this set
And we can use recursion to do divide and conquer work.
public static List<Integer> permutationByRank(int n, int k){
//prepare the set
List<Integer> list = new ArrayList<Integer>();
for(int i=1; i<=n; i++)
list.add(i);
//calculate the group size
int size = factor(n-1);
return permuByRankUtil(list, k-1, size);
}
/*
* here k starts at 0 to n!-1 for easy computing purpose
*/
public static List<Integer> permuByRankUtil(List<Integer> nums, int k, int f){
int size = nums.size();
//base case
if(size==1)
return nums;
else{
//decide group index
int index = k/f;
int first = nums.remove(index);
List<Integer> re = permuByRankUtil(nums, k%f, f/(size-1));
re.add(0, first);
return re;
}
}
No comments:
Post a Comment