首页 > 其他 > 详细

[LintCode] Permuation Index

时间:2015-10-05 14:12:24      阅读:171      评论:0      收藏:0      [点我收藏+]

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

 

[LintCode] Permuation Index

原文:http://www.cnblogs.com/changchengxiao/p/4855643.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!