[Leetcode] DP--629. K Inverse Pairs Array

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.
reference the tutorial of the solution; https://leetcode.com/articles/k-inverse-pairs-array/
   very great explanation for 8 approaches, I only came up with the naive method and the recursive method
 
(1) Define the subproblem
    dp[i][j] as the given integer i and the inverse pairs number j
dp[n][k] is the final answer
(2) Find the recursion
dp[i][j] =    dp[i-1][j-p]   for k = 0 to min(i-1, j)
 
(3) Get the base case
 dp[0][j] = 0 for j = 0 to n
 dp[i][0] = 1 for i = 0 to n
 
 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. 

further to observe that if we use accumulated sum for dp[i][j], we can have
dp[i−1][j]+dp[i−1][j−i] if j−i≥0. Otherwise, we add all the elements of the previous row upto the current column j being considered.
 
 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

 

posted @ 2017-06-26 14:03  安新  阅读(313)  评论(0编辑  收藏  举报