[Swift]LeetCode629. K個逆序對數組 | K Inverse Pairs Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-tcpgquyp-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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.git

We define an inverse pair as following: For ith and jthelement in the array, if i < j and a[i] > a[j] then it's an inverse pair; Otherwise, it's not.github

Since the answer may be 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:spa

Input: n = 3, k = 1
Output: 2
Explanation: 
The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. 

Note:code

  1. The integer n is in the range [1, 1000] and k is in the range [0, 1000].

給出兩個整數 n 和 k,找出全部包含從 1 到 n 的數字,且剛好擁有 k 個逆序對的不一樣的數組的個數。htm

逆序對的定義以下:對於數組的第i個和第 j個元素,若是滿i < j且 a[i] > a[j],則其爲一個逆序對;不然不是。blog

因爲答案可能很大,只須要返回 答案 mod 109 + 7 的值。element

示例 1:

輸入: n = 3, k = 0
輸出: 1
解釋: 
只有數組 [1,2,3] 包含了從1到3的整數而且正好擁有 0 個逆序對。

示例 2:

輸入: n = 3, k = 1
輸出: 2
解釋: 
數組 [1,3,2] 和 [2,1,3] 都有 1 個逆序對。

說明:

  1.  n 的範圍是 [1, 1000] 而且 k 的範圍是 [0, 1000]。

Runtime: 280 ms
Memory Usage: 25.2 MB
 1 class Solution {
 2     func kInversePairs(_ n: Int, _ k: Int) -> Int {
 3         var M:Int = 1000000007
 4         var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:k + 1),count:n + 1)
 5         dp[0][0] = 1
 6         if n >= 1
 7         {
 8             for i in 1...n
 9             {
10                 dp[i][0] = 1
11                 if k >= 1
12                 {
13                     for j in 1...k
14                     {
15                         dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % M
16                         if j >= i
17                         {
18                             dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + M) % M
19                         }
20                     }
21                 }
22             }
23         }        
24         return dp[n][k]
25     }
26 }
相關文章
相關標籤/搜索