标签:put man win href const sid further blog tps
Given two integers n
and k
, find how many different arrays consist of numbers from 1
to n
such that there are exactly k
inverse pairs.
We define an inverse pair as following: For ith
and jth
element in the array, if i
< j
and a[i]
> a[j]
then it‘s an inverse pair; Otherwise, it‘s not.
Since the answer may very large, the answer should be modulo 109 + 7.
Example 1:
Input: n = 3, k = 0 Output: 1 Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.
Example 2:
Input: n = 3, k = 1 Output: 2 Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
Solution:
This problem‘s dp solution is challenging to construct
1 M = 10**9 + 7 2 dp = [[0]*(k+1) for i in range(0,n+1)] 3 4 #print ("dp: ", dp) 5 for i in range(1, n+1): 6 for j in range(0, k+1): 7 #print ("dp: ", i, j, dp[i][j]) 8 if j == 0: 9 dp[i][j] = 1 10 #print ("atttt: ", i, j, dp[i][0]) 11 12 else: 13 for p in range(0, min(j, i-1)+1): 14 dp[i][j] = (dp[i][j] + dp[i-1][j-p])%M 15 #print ("daaaap: ", i, j, dp[i][0]) 16 17 return dp[n][k]
It has TLE problem
2.
1 M = 10**9 + 7 2 dp = [[0]*(k+1) for i in range(0,n+1)] 3 4 #print ("dp: ", dp) 5 for i in range(1, n+1): 6 for j in range(0, k+1): 7 #print ("dp: ", i, j, dp[i][j]) 8 if j == 0: 9 dp[i][j] = 1 10 #print ("atttt: ", i, j, dp[i][0]) 11 12 else: 13 if j >= i: 14 val = (dp[i-1][j] + M - dp[i-1][j-i]) % M 15 else: 16 val = (dp[i-1][j] + M - 0) % M 17 dp[i][j] = (dp[i][j-1] + val)%M 18 #print ("daaaap: ", i, j, dp[i][0]) 19 20 if k > 0: 21 return (dp[n][k] + M - dp[n][k-1])%M 22 else: 23 return (dp[n][k] + M - 0)%M
[Leetcode] DP--300. 629. K Inverse Pairs Array
标签:put man win href const sid further blog tps
原文地址:http://www.cnblogs.com/anxin6699/p/7080261.html