1. 程式人生 > >數列還原(全排列)

數列還原(全排列)

for rip 幫助 個數字 item [0 str pan subject

題目描述

牛牛的作業薄上有一個長度為 n 的排列 A,這個排列包含了從1到n的n個數,但是因為一些原因,其中有一些位置(不超過 10 個)看不清了,但是牛牛記得這個數列順序對的數量是 k,順序對是指滿足 i < j 且 A[i] < A[j] 的對數,請幫助牛牛計算出,符合這個要求的合法排列的數目。

輸入描述:

每個輸入包含一個測試用例。每個測試用例的第一行包含兩個整數 n 和 k(1 <= n <= 100, 0 <= k <= 1000000000),接下來的 1 行,包含 n 個數字表示排列 A,其中等於0的項表示看不清的位置(不超過 10 個)。

輸出描述:

輸出一行表示合法的排列數目。

示例1

輸入

5 5

4 0 0 2 0

輸出

2

分析:

  遍歷出缺少的數字,統計缺少的數字所有的排列組合。將每一種排列組合按順序插入原數組中,然後統計順序對,如果順序對符合要求,則題目所求合法排列數加1

  這道題值得思考的地方是全排列

def getMissData(nums):
    res = [0]*(len(nums)+1)
    for i in nums:
        res[i] = 1
    ans = []
    for i in range(1,len(res)):
        if res[i] == 0:
            ans.append(i)
    
return ans def getPermutation(nums,i,n,perm): if i == n: perm.append(nums) for j in range(i,n): tmp = nums[:] tmp[i],tmp[j] = tmp[j],tmp[i] getPermutation(tmp,i+1,n,perm) def getCntPair(nums): cnt = 0 for i in range(len(nums)): for j in range(0,i):
if nums[j] < nums[i]: cnt += 1 return cnt n,k = map(int,raw_input().strip().split()) nums = map(int,raw_input().strip().split()) missData = getMissData(nums) perms = [] getPermutation(missData,0,len(missData),perms) cnt = 0 ans = 0 for perm in perms: idx = 0 tmp = nums[:] for i in range(len(tmp)): if tmp[i] == 0: tmp[i] = perm[idx] idx += 1 cnt = getCntPair(tmp) if cnt == k: ans += 1 print(ans)

數列還原(全排列)