1. 程式人生 > >leetCode 60.Permutation Sequence (排列序列) 解題思路和方法

leetCode 60.Permutation Sequence (排列序列) 解題思路和方法

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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

思路:這一題還是比較難,暴力完全是找死的,超時沒二話。但是數學歸納的方法不是每個人都能想到,看了很多資料,也才剛理解了一些思想。

規律:已知n的值,學過排列組合知道共有n!種排列。
第一位每個數字開頭的序列都有(n-1)!個序列,因此n個數字所以共有n!個序列。
以此類推,第二位每一個數開頭都有(n-2)!個序列。

具體程式碼如下:

public class Solution {
    String str = "";
    public String getPermutation(int n, int k) {
    	int[] num = new int[n];
        int[] data = new int[n];//存階乘的資料
        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(--i > -1){//迴圈得到各位數字
        	int k1 = k/data[i];
        	int p = k1+(n-1-i);//數字的位置
        	swap(n-1-i,p,num);
        	if((k = k %data[i]) == 0)//k==0結束
        		break;
        }
        for(int x:num)//得到str
        	str += x;
        return str;
    }
    //將資料插入,後面的依次後移
    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;
    }
}