Skip to content

Commit ba21fe7

Browse files
committed
Add can_partition_k_subsets
1 parent 9ab5308 commit ba21fe7

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// 698. Partition to K Equal Sum Subsets, Medium
2+
// https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
3+
impl Solution {
4+
pub fn can_partition_k_subsets(mut nums: Vec<i32>, k: i32) -> bool {
5+
let sum = nums.iter().sum::<i32>();
6+
if sum % k != 0 {
7+
return false;
8+
}
9+
let target = sum / k;
10+
11+
nums.sort();
12+
if nums[nums.len() - 1] > target {
13+
return false;
14+
}
15+
16+
fn backtrack(nums: &Vec<i32>, target: i32, pos: usize, next: i32, used: &mut Vec<bool>) -> bool {
17+
if used.iter().all(|x| *x) {
18+
return true;
19+
}
20+
21+
for i in pos..nums.len() {
22+
if used[i] || next + nums[i] > target {
23+
continue;
24+
}
25+
26+
let next = (next + nums[i]) % target;
27+
used[i] = true;
28+
if backtrack(nums, target, if next == 0 { 0 } else { i + 1 }, next, used) {
29+
return true;
30+
}
31+
used[i] = false;
32+
}
33+
34+
false
35+
}
36+
37+
backtrack(&nums, target, 0, 0, &mut vec![false; nums.len()])
38+
}
39+
}
40+
41+
struct Solution {}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
use super::*;
46+
47+
#[test]
48+
fn test_can_partition_k_subsets() {
49+
assert_eq!(Solution::can_partition_k_subsets(vec![4, 3, 2, 3, 5, 2, 1], 4), true);
50+
}
51+
52+
#[test]
53+
fn test_can_partition_k_subsets2() {
54+
assert_eq!(Solution::can_partition_k_subsets(vec![1, 2, 3, 4], 3), false);
55+
}
56+
57+
#[test]
58+
fn test_can_partition_k_subsets3() {
59+
assert_eq!(Solution::can_partition_k_subsets(vec![4, 3, 2, 3, 5, 2, 0], 4), false);
60+
}
61+
}

src/leetcode/challenge/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod break_palindrome;
2+
mod can_partition_k_subsets;
23
mod find_max_consecutive_ones;
34
mod intersect;
45
mod max_length;

0 commit comments

Comments
 (0)