标签:
题目链接:https://leetcode.com/problems/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,
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.
思路:
从左往右计算,先计算最高位。 应该为k/(n-1)! ,下一位应该是(k%(n-1)!)/(n-2)!,以此类推。
算法:
public String getPermutation(int n, int k) { int nums[] = new int[n]; int pCount=1; for(int i=0;i<nums.length;i++){ nums[i] = i+1; pCount *= (i+1);//n! } k--;//下标从0开始 String res = ""; for(int i=0;i<n;i++){ pCount /=n-i;//(n-i-1)! int r = k/pCount; res+=nums[r];//第r小的元素 for(int j=r;j<n-1-i;j++){ //获取第r小的元素 所以将已经用过的元素覆盖 nums[j] = nums[j+1]; } k = k%pCount; } return res; }
【Leetcode】Permutation Sequence
标签:
原文地址:http://blog.csdn.net/yeqiuzs/article/details/51542413