60. Permutation Sequence (JAVA)

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 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.
  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

规律:在n!个排列中,除去第一位,后几位共有(n-1)!个排列,所以第一位的元素总是(n-1)!一组出现的。那么,第k行第一位的值就=nums[(k-1)/(n-1)!]。

阶乘的下一个状态依赖上一个状态,所以可以用动态规划存储阶乘的结果。

另外注意,JAVA中两个int数a,b除法的结果如果要保留Double,正确的写法是(Double) a/b,而不能是(Double) (a/b),后者由于先做的整数除法,返回的是截尾的整数。

class Solution {
    public String getPermutation(int n, int k) {
        int[] dp = new int[n];
        dp[0] = 1;
        for(int i = 1; i < n; i++){
            dp[i] = i*dp[i-1]; //阶乘
        }
        
        Boolean[] flag = new Boolean[n];
        for(int i = 0; i < n; i++){
            flag[i] = false; 
        }
        
        String s = "";
        int cnt;
        int num;
        for(int i = 0; i < n ; i++){ //确定每一位的数字
            cnt = (int) Math.ceil((double) k/dp[n-i-1]); //剩余数字(flag为false)里第cnt大的那个
            k -= (cnt-1) * dp[n-i-1];
            num = 0;
            for(; cnt>0; num++){
                if(flag[num]) continue;
                cnt--; //flag为false计1
            }
            flag[num-1] = true;
            s += num;
        }
        return s;
    }
}

 

posted on 2019-05-22 19:03  joannae  阅读(102)  评论(0编辑  收藏  举报

导航