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 would be between 1 and 9 inclusive.
Idea: This problem is still relatively difficult, violence is to find dead, time-out did not gave. But the method of mathematical induction is not everyone can think, read a lot of information, also just understand some ideas.
Law: Known n values, learned permutations and combinations know a common n! Species arrangement.
The first sequence with each number starts with (N-1)! sequence, so n numbers so there's a n! A sequence.
And so on, the second digit starts with every number (N-2)! A sequence.
The specific code is as follows:
public class Solution { String str = ""; Public String getpermutation (int n, int k) { int[] num = new Int[n]; int[] data = new int[n];//the dataset of the factorial, int i = 0; for (; i < n; i++) { num[i] = i+1; if (i = = 0) data[i] = 1; else{ Data[i] = data[i-1]*i; } } k--; while (---->-1) {//loop get the numbers int k1 = k/data[i]; int p = k1+ (n-1-i);//Digital position swap (n-1-i,p,num); if (k = k%data[i]) = = 0)//k==0 end break ; } for (int x:num)//Get str str + = x; return str; } Insert the data, followed by the public Void swap (int i,int j,int[] num) { int m = num[j]; for (int k=j;k>i;k--) num[k]=num[k-1]; num[i]=m;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 60.Permutation Sequence (permutation sequence) thinking and method of solving problems