The set [1, 2, 3 ,...,N] Contains a totalN! Unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie,N= 3 ):
- "123"
- "132"
- "213"
- "231"
- "312"
- "321"
GivenNAndK, ReturnKTh permutation sequence.
Https://oj.leetcode.com/problems/permutation-sequence/
Computing 1 ~ K of N numbers
Idea 1: Count from small to large until the K. It must be time-out ..
Idea 2: Calculate the k-th order based on the rule.
Analysis: 1 ~ N total N! (N-1 )! , Starting with 2 (n-1 )! (N-1) at the beginning of... n )! . Therefore, K/(n-1) is used )! The first number is determined, and the number is removed in turn (n-1 )! K % (n-1) in the number )! Number.
Idea 2 code:
public class Solution { public String getPermutation(int n, int k) { int[] num = new int[n]; int permSum = 1; for (int i = 0; i < n; i++) { num[i] = i + 1; permSum *= (i + 1); } StringBuilder sb = new StringBuilder(); k--;//change to base 0 for (int i = 0; i < n; i++) { permSum = permSum / (n - i); int selected = k / permSum; sb.append(num[selected]); for (int j = selected; j < n - i - 1; j++) num[j] = num[j + 1]; k = k % permSum; } return sb.toString(); } public static void main(String[] args) { System.out.println(new Solution().getPermutation(4, 10)); }}
Refer:
Http://blog.csdn.net/havenoidea/article/details/12837441
Http://www.cnblogs.com/TenosDoIt/p/3721918.html