LeetCode 629. K inversions array

Topic links: https://leetcode-cn.com/problems/k-inverse-pairs-array/

Subject to the effect

  slightly.

analysis

  First, the maximum reverse order n 1 ~ n which is the number that can be generated for n * (n - 1) / 2 pairs.
  Provided dp [i] [j] represents 1 ~ i j can produce several types of arrangement of the reverse order.
  Here the definition of what if the index is negative, this one is zero.
  In considering the following fact: the sequence 1,2,3,4,5 and 2,5,7,9,10, in this issue, I can say that these two sequences are equivalent, because to produce reverse order the nature of the relationship between the size rather than the number of actual size.
  Now consider the state transition equation.
  First, when j> i * (i - 1) / 2 when, dp [i] [j] = 0.
  Secondly, when j = 0, dp [i] [0] = 1, only a method along the row.
  Above determined initial state.
  For other dp [i] [j], if we consider the release of a large number of k in the first team, then the number contributed k - 1 Dui reverse order, the remaining i - 1 different numbers can be converted into sub-problems, i.e. dp [i - 1] [j - k].
  Similarly we can put the number of the other team head, respectively, seek what contribution, the state transition equation can be obtained: $$ dp [i] [j] = \ sum_ {k = max (0, j - i + 1)} ^ {j} dp [i - 1] [k] $$
  Careful observation of two longitudinal relation can be found: $$ dp [i] [j] = dp [i] [j - 1] + dp [i - 1] [j] - dp [i - 1] [max (0 , j - i + 1) - 1] $$
  But do not push this formula can do, and to put forward a prefix.

code show as below

 1 class Solution {
 2     int dp[2][1007], mod = 1e9 + 7, now = 0;
 3 public:
 4     int kInversePairs(int n, int k) {
 5         dp[now][0] = 1;
 6         
 7         for(int i = 1; i <= n; ++i) {
 8             now = !now;
 9             dp[now][0] = 1;
10             for(int j = 1; j <= k; ++j) {
11                 if(2 * j > i * (i - 1)) break;
12                 dp[now][j] = (dp[now][j - 1] + dp[!now][j]) % mod;
13                 if(j - i >= 0) dp[now][j] = (dp[now][j] - dp[!now][j - i] + mod) % mod;
14             }
15         }
16         
17         return dp[now][k];
18     }
19 };
View Code

 

Guess you like

Origin www.cnblogs.com/zaq19970105/p/11183886.html