Permutation Sequence, Solution

 

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.

 1     String getPermutation(int n, int k) {  

 2         Vector<Integer> num = new Vector<Integer>(n);

 3         StringBuffer out = new StringBuffer();

 4         int max = 1;

 5         for(int i = 0; i < n; i ++){

 6             num.add(i + 1);

 7             max *= i + 1;

 8         }

 9         int choosed = 0;

10         k -= 1;

11         for(int i = 0; i < n; i ++){

12             max /= (n - i);

13             choosed = k / max;

14             out.append(num.elementAt(choosed));

15             num.remove(choosed);

16             out.append(" ");

17             k = k % max;

18         }

19         

20         return out.toString();

21     }

 

你可能感兴趣的:(sequence)