Permutation Sequence

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,

思路:

假设有n个元素,第K个permutation是
a1, a2, a3, .....   ..., an
那么a1是哪一个数字呢?
那么这里,我们把a1去掉,那么剩下的permutation为
a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道
设变量K1 = K
a1 = K1 / (n-1)!
同理,a2的值可以推导为
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
 .......
a(n-1) = K(n-1) / 1!
K(n-1) = K(n-2) /2!
an = K(n-1)

我的代码:

public class Solution {
    public String getPermutation(int n, int k) {
        int[] num = new int[n];
        int count = 1;
        for(int i=0; i<n; i++)
        {
            num[i] = (i+1);
            count *= (i+1);
        }
        k--;
        StringBuffer target = new StringBuffer();
        for(int i=0; i<n; i++)
        {
            count /= (n-i);
            int selecked = k/count;
            target.append(num[selecked]);
            for(int j=selecked; j<n-1-i; j++)
            {
                num[j] = num[j+1];
            }
            k = k%count;
        }
        return target.toString();
    }
}
View Code

学习之处:

  • 一遇到这种数学推导规律的问题,就不愿意思考,以后改掉这个坏毛病。
  • 用num进行标记那些数字访问过了,访问过了就替换掉了,这种思路好棒呀,省的再用hashmap进行存储
  • 改变不好的习惯 第一天
原文地址:https://www.cnblogs.com/sunshisonghit/p/4460417.html