标签:
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.
思路分析:这题主要是需要找规律,n个数的permutation总共有n!个,如果当前长度是n,我们知道每个相同的起始元素对应(n-1)!个permutation,也就是(n-1)!个permutation后会换一个起始元素。因此,把k%(n-1)!得到的是剩余部分的permutation index,k/(n-1)!可以返回num的index(即1,2,3...n中的哪一个),如此操作,初始令round=n-1, 不断执行k%(n-1)!并执行round--,直到round=0,就可以拼出所求的permutation sequence。注意初始要执行k--,这样k就是从0开始,numIdx也可以从0开始,这样才可以求出争取的numIdx。空间复杂度O(n),时间复杂度O(n^2)当然这题也可以递归实现。
AC Code
public class Solution { public String getPermutation(int n, int k) { //0108 if(n<=0) return ""; String res = ""; int factor = 1; for(int i = 2; i < n; i++){ factor *= i; //facotr = (n-1)! } int round = n-1; ArrayList<Integer> nums = new ArrayList<Integer>(); for(int i = 1; i <=n; i++){ nums.add(i); } k--; while(round>=0){ int numIdx = k / factor; k = k % factor; res += nums.get(numIdx); nums.remove(numIdx); if(round > 0){ factor /= round; } round--; } return res; } }reference: http://codeganker.blogspot.com/2014/03/permutation-sequence-leetcode.html
标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/45149055