[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.
public class Solution { public String getPermutation(int n, int k) { // http://www.cnblogs.com/tenosdoit/p/3721918.html List<String> num = new LinkedList<>(); int perm = 1; // n! for (int i = 0; i < n; i++) { num.add(String.valueOf(i+1)); perm *= i+1; } String result = ""; k--; // Changed to 0-based for (int i = 0; i < n; i++) { perm /= n-i; int index = k/perm; String val = num.remove(index); // Delete the selected number and recontruct the 'num' list result += val; k = k%perm; } return result; } }
No comments:
Post a Comment