博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Swift]LeetCode629. K个逆序对数组 | K Inverse Pairs Array
阅读量:4577 次
发布时间:2019-06-08

本文共 2109 字,大约阅读时间需要 7 分钟。

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝()
➤GitHub地址:
➤原文地址: 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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 jthelement 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 be very large, the answer should be modulo 109 + 7.

Example 1:

Input: n = 3, k = 0Output: 1Explanation: 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 = 1Output: 2Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. 

Note:

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

给出两个整数 n 和 k,找出所有包含从 1 到 n 的数字,且恰好拥有 k 个逆序对的不同的数组的个数。

逆序对的定义如下:对于数组的第i个和第 j个元素,如果满i < j且 a[i] > a[j],则其为一个逆序对;否则不是。

由于答案可能很大,只需要返回 答案 mod 109 + 7 的值。

示例 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] = 111                 if k >= 112                 {13                     for j in 1...k14                     {15                         dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % M16                         if j >= i17                         {18                             dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + M) % M19                         }20                     }21                 }22             }23         }        24         return dp[n][k]25     }26 }

 

转载于:https://www.cnblogs.com/strengthen/p/10473028.html

你可能感兴趣的文章
安卓|五大逆向软件下载
查看>>
5 OK6410裸机调试(不用Jlink)
查看>>
“模板”学习笔记(5)-----编译器在处理函数模板的时候都干了啥
查看>>
教你用shell写CGI程序
查看>>
窗口 对话框 Pop Dialog 示例
查看>>
ubuntu(centos) server安装vmware tools
查看>>
数据结构之最大不重复串
查看>>
为什么要配置sdk-tools/platform-toools?
查看>>
自己动手开发更好用的markdown编辑器-07(扩展语法)
查看>>
队列的循环队列
查看>>
程序中的日期格式
查看>>
大众点评CAT错误总结以及解决思路
查看>>
从0开始学爬虫3之xpath的介绍和使用
查看>>
vim下正则表达式的非贪婪匹配
查看>>
一个python的计算熵(entropy)的函数
查看>>
spring源码学习——spring整体架构和设计理念
查看>>
模拟window系统的“回收站”
查看>>
报文格式【定长报文】
查看>>
RDLC报表钻取空白页问题
查看>>
多路电梯调度的思想
查看>>