lintcode-easy-Permutation 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.

Given [1,2,4], return 1.

 

思路:

统计最高位之后最高位数小的个数,(n-1)!乘以这个数,就得到最高位比现在的数最高位小的时候的所有组合数。再把最高位去掉,重复这个过程,就得到了结果。

public class Solution {
    /**
     * @param A an integer array
     * @return a long integer
     */
    public long permutationIndex(int[] A) {
        // Write your code here
        if(A == null || A.length == 0)
            return (long) 0;
        
        long result = 0;
        
        for(int i = 0; i < A.length; i++){
            long num = 0;
            for(int j = i + 1; j < A.length; j++){
                if(A[j] < A[i])
                    num++;
            }
            
            result += num * fac(A.length - i - 1);
        }
        
        return result + 1;
    }
    
    public long fac(int num){
        if(num == 0 || num == 1)
            return 1;
        
        long result = 1;
        
        for(int i = 1; i <= num; i++)
            result *= i;
        
        return result;
    }
}

 

posted @ 2016-03-03 13:02  哥布林工程师  阅读(134)  评论(0编辑  收藏  举报