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 < 2) return len; vector<long long> factorial(len, 1); for(long long i = len - 2;i >= 0;--i) factorial[i] = factorial[i + 1] * (len - 1 - i); long long res = 1; for(long long i = 0;i < len;++i){ long long num = 0; for(long long j = i + 1;j < len;++j) if(A[j] < A[i]) ++num; res += num * factorial[i]; } return res; } };
时间: 2024-11-04 23:15:26