Permutation Sequence

来源:互联网 发布:淘宝哪家iphone 编辑:程序博客网 时间:2024/06/05 08:04

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 will be between 1 and 9 inclusive.

public static String getPermutation(int n, int k) {// initialize all numbersArrayList<Integer> numberList = new ArrayList<Integer>();for (int i = 1; i <= n; i++) {numberList.add(i);}// change k to be indexk--;// set factorial of nint mod = 1;for (int i = 1; i <= n; i++) mod = mod * i;String result = "";// find sequencefor (int i = 0; i < n; i++) {mod = mod / (n - i);// find the right number(curIndex) ofint curIndex = k / mod;// update kk = k % mod;// get number according to curIndexresult += numberList.get(curIndex);// remove from listnumberList.remove(curIndex);}return result.toString();}


0 0
原创粉丝点击