Leetcode 698. Partition to K Equal Sum Subsets
The problem “Partition to K Equal Sum Subsets” is defined as follows:
Given an array of integers nums
and an integer k
, determine if it is possible to partition this array into k
non-empty subsets whose sums are all equal.
We need to partition the array into k
subsets such that each subset has the same sum. Here’s the strategy:
k
, then it’s impossible to partition as required.target = total_sum / k
.#include <vector>
#include <algorithm>
class Solution {
public:
bool canPartitionKSubsets(std::vector<int>& nums, int k) {
int totalSum = 0;
for (int val : nums) {
totalSum += val;
}
if (totalSum % k != 0) return false;
int target = totalSum / k;
std::sort(nums.begin(), nums.end(), std::greater<int>());
std::vector<bool> used(nums.size(), false);
return backtrack(nums, used, k, 0, 0, target);
}
private:
bool backtrack(const std::vector<int>& nums, std::vector<bool>& used, int k, int currentSum, int startIndex, int target) {
if (k == 1) return true; // Only one subset remaining, it must be valid
if (currentSum == target) {
return backtrack(nums, used, k - 1, 0, 0, target);
}
for (int i = startIndex; i < nums.size(); ++i) {
if (used[i] || currentSum + nums[i] > target) continue;
used[i] = true;
if (backtrack(nums, used, k, currentSum + nums[i], i + 1, target)) {
return true;
}
used[i] = false;
// Optimization: If adding the current element can't satisfy the condition, no need to try other elements
if (currentSum == 0) return false;
}
return false;
}
};
O(n log n)
where n
is the number of elements in the array.O(2^n)
subsets to check in the worst case, but pruning and sorting elements reduce the actual number of checks significantly.O(k * 2^n)
. However, typical cases will be faster due to early exits on invalid paths.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?