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.
class Solution {
public:
/**
* @param A an integer array
* @return a long integer
*/
long long permutationIndex(vector<int>& A) {
long long len = A.size();
if(len < ) return len; vector<long long> factorial(len, );
for(long long i = len - ;i >= ;--i)
factorial[i] = factorial[i + ] * (len - - i); long long res = ;
for(long long i = ;i < len;++i){
long long num = ;
for(long long j = i + ;j < len;++j)
if(A[j] < A[i]) ++num;
res += num * factorial[i];
}
return res;
}
};