[lintcode easy]Permutation Index

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.

Example

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

////

这道题有点难理解,求数列在其全排列组合位于第几位。

思路参考别人的,并不需要求出所有的排列组合。

对于某一个给定的位数A[i],需要判断在它后面有几个小于它的数,记下这个数字和A[i]所在的位置。

比如对于一个四位数,5316  , 第一位后面有2小于它的数,如果这两个数排在第一位,那么(1和3)各有3!的排列组合数小于(5316).

同理,对于第二位,其后有1个小于它的数,如果它放在第二位,那么有2!种排列。

因此判断一个给定数位于排列组合的第几位,则可以按照以下公式进行

count1*(A.length-1)!+count2*(A.length-2)!+......+countn*(0)!

public class Solution {
    /**
     * @param A an integer array
     * @return a long integer
     */
    public long permutationIndex(int[] A) {
        // Write your code here
        
        long index=0;
        
        int p;
        for(int i=0;i<A.length;i++)
        {
            long count=0;
            long factor=1;
            for(int j=i+1;j<A.length;j++)
            {
                if(A[j]<A[i])
                {
                    count++;
                }
            }
          
            if(count>0)
            {
                p=A.length-i-1;
                for(int q=1;q<=p;q++)
                {
                    factor=factor*q;
                }
            }
            
            
            index=index+(count*factor);

        }
        
        index=index+1;
        return index;
    }
}

 

posted on 2015-12-03 03:40  一心一念  阅读(680)  评论(0编辑  收藏  举报

导航