- Permutation Index
中文English
Given a permutation which contains no repeated number, find its index in all the permutations of these numbers, which are ordered in lexicographical order. The index begins at 1.
Example
Example 1:
Input:[1,2,4]
Output:1
Example 2:
Input:[3,2,1]
Output:6
解法1:
参考网上解法。举个例子[3,7,4,9,1]。
而第i个元素,比原数组小的情况有多少种,其实就是A[i]右侧有多少元素比A[i]小,乘上A[i]右侧元素全排列数,即A[i]右侧元素数量的阶乘。i从右往左看,比当前A[i]小的右侧元素数量分别为1,1,2,1,所以最终字典序在当前A之前的数量为1×1!+1×2!+2×3!+1×4!=39,故当前A的字典序为40。
上面的1,2,3,4分别对应9,4,7,3,即每个元素右侧元素有多少个元素。
怎么理解这个阶乘呢?以i=1为例,此时A[1]=7,右侧有2个元素比它小,即4和1。把每个比它小的元素跟它对调,以4为例,有3,4,7,9,1。这里7,9,1可以混着排,共有3!种,这里3就是i=1右侧的元素。而1也可以跟7互换,故有2×3!。
代码如下:
class Solution {
public:
/**
* @param A: An array of integers
* @return: A long integer
*/
long long permutationIndex(vector<int> &A) {
int n = A.size();
if (n <= 1) return n;
long long result = 1;
long long currFactorial = 1;
for (int i = n - 2; i >= 0; --i) {
int smallers = 0;
for (int j = i + 1; j < n; ++j) {
if (A[j] < A[i]) smallers++;
}
result += currFactorial * smallers;
currFactorial *= n - i;
}
return result;
}
};
本文介绍了一种算法,用于计算给定无重复数字排列在其所有字典序排列中的索引位置。通过计算右侧比当前元素小的元素数量及其阶乘,得出排列在字典序中的具体位置。
454

被折叠的 条评论
为什么被折叠?



