mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
rs: add «629. K Inverse Pairs Array»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5a4efd75db
commit
2c3f0e2255
1 changed files with 26 additions and 0 deletions
26
rs/k-inverse-pairs-array.rs
Normal file
26
rs/k-inverse-pairs-array.rs
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
impl Solution {
|
||||||
|
pub fn k_inverse_pairs(n: i32, k: i32) -> i32 {
|
||||||
|
let MOD = 1000000007;
|
||||||
|
|
||||||
|
let idx = |i, j| (i * (k + 1) + j) as usize;
|
||||||
|
let get = |dp: &[i32], i: i32, j: i32| {
|
||||||
|
if i < 0 || i > n || j < 0 || j > k {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
dp[idx(i, j)]
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut dp = vec![0; ((n + 1) * (k + 1)) as usize];
|
||||||
|
for (i, j) in (1..=n).flat_map(|i| (0..=k).map(move |j| (i, j))) {
|
||||||
|
if j == 0 {
|
||||||
|
dp[idx(i, j)] = 1;
|
||||||
|
} else {
|
||||||
|
let val = (get(&dp, i - 1, j) + MOD - get(&dp, i - 1, j - i)) % MOD;
|
||||||
|
dp[idx(i, j)] = (get(&dp, i, j - 1) + val) % MOD;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(dp[idx(n, k)] + MOD - get(&dp, n, k - 1)) % MOD
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue