[LintCode] Permuation Index

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;
    }
};

 

posted @ 2015-10-05 13:26  xchangcheng  阅读(185)  评论(0编辑  收藏  举报