题目描述:
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
题目思路:
Given [1,2,4], return 1.
这题的思路就是一个一个求,比如example中,要先求出1是以1开头的3位数组中的第几个,然后求2是以2开头的2位数组中的第几个,以此类推,然后把说得结果加起来就行了。
Mycode (AC = 13ms):
class Solution {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndex(vector<int>& A) {
// Write your code here
return permutationIndex(A, 0) + 1;
}
long long permutationIndex(vector<int>& A, int idx) {
if (idx >= A.size()) {
return 0;
}
// find A[idx] is x-th smallest in the index idx~end
long long order = 0;
for (int i = idx + 1; i < A.size(); i++) {
if (A[i] < A[idx]) {
order++;
}
}
// find the number of permutation for A[idx + 1..end]
long long base = 1;
for (int i = 1; i < A.size() - idx; i++) {
base *= (long long)i;
}
return base * order + permutationIndex(A, idx + 1);
}
};