#197 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.

题目思路:

这题的思路就是一个一个求,比如example中,要先求出1是以1开头的3位数组中的第几个,然后求2是以2开头的2位数组中的第几个,以此类推,然后把说得结果加起来就行了。

Mycode (AC = 13ms):

class Solution {
public:
    /**
     * @param A an integer array
     * @return a long integer
     */
    long long permutationIndex(vector<int>& A) {
        // Write your code here
        return permutationIndex(A, 0) + 1;
    }
    
    long long permutationIndex(vector<int>& A, int idx) {
        if (idx >= A.size()) {
            return 0;
        }
        
        // find A[idx] is x-th smallest in the index idx~end
        long long order = 0;
        for (int i = idx + 1; i < A.size(); i++) {
            if (A[i] < A[idx]) {
                order++;
            }
        }
        
        // find the number of permutation for A[idx + 1..end]
        long long base = 1;
        for (int i = 1; i < A.size() - idx; i++) {
            base *= (long long)i;
        }
        
        return base * order + permutationIndex(A, idx + 1);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值