60. Permutation Sequence

来源:互联网 发布:北京银行网银mac版 编辑:程序博客网 时间:2024/05/01 14:31

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.

其实是一个排列组合找规律问题。
对于第一个数字,其他2~n个数字有(n-1)!个排列,对于k为,1~(n-1)!,第一个数为1;为(n-1)!+1~2*(n-1)!,是2;以此类推
之后要更新k,k对第二个数字是 k -= i*(n-1)!
对于第i个数字,其后数字有(n-i)!个排列,对于之后余下的n-i个数,k为1~(n-i)!,i+1个数字是剩余(n-i)个数中的第一个

public class Solution {   public String getPermutation(int n, int k) {           if (n < 1) return "";        ArrayList<Integer> num =new ArrayList<Integer>();        for (int i = 1; i <= n; i++) {            num.add(i);        }        int f = 1;        for (int i = 1; i <= n; i++) {            f = f*i;        }        StringBuilder r = new StringBuilder();        for (int i = 0; i < n; i++) {            f = f/(n-i);            int index = (k-1)/f;            r.append(num.get(index));            num.remove(index);            k = k - f*index;        }        return r.toString();    }  }
0 0
原创粉丝点击