Backtracking Algorithm Practice: Partitioning k Subsets
This article will resolve
LeetCode | Difficulty |
---|---|
698. Partition to K Equal Sum Subsets | 🟠 |
Prerequisites
Before reading this article, you should first learn:
I previously mentioned that backtracking is the most useful algorithm in written exams. Whenever you have no idea, use backtracking to solve it brute-force. Even if you can't pass all test cases, you might pass some. The technique of backtracking is not difficult; it's the process of exhausting a decision tree. Just "make a choice" before recursion and "undo the choice" after recursion.
However, even with brute-force, different approaches have their pros and cons. This article will explore a classic backtracking problem, LeetCode Problem 698: Partition to K Equal Sum Subsets. This problem can help you gain a deeper understanding of the backtracking mindset and write backtracking functions skillfully.
The problem is very simple:
Given an array nums
and a positive integer k
, determine if nums
can be partitioned into k
subsets with equal sum.
The function signature is as follows:
boolean canPartitionKSubsets(int[] nums, int k);
bool canPartitionKSubsets(vector<int>& nums, int k);
def canPartitionKSubsets(nums: List[int], k: int) -> bool:
func canPartitionKSubsets(nums []int, k int) bool {
var canPartitionKSubsets = function(nums, k) {
};
Thought Exercise
We previously discussed the Subset Sum Partition problem, where we needed to divide a set into two equal subsets. This problem can be transformed into a knapsack problem and solved using dynamic programming techniques.
Why can dividing a set into two equal subsets be transformed into a knapsack problem and solved with dynamic programming, but dividing it into k
equal subsets cannot be transformed into a knapsack problem and can only be solved using backtracking with brute-force enumeration? Please try to think about this on your own first.
Answer to Thought Exercise
Why can dividing into two equal subsets be transformed into a knapsack problem?
In the scenario of the Subset Sum Partition problem, there is a knapsack and several items, each with two choices: either "put in the knapsack" or "not put in the knapsack." When dividing the original set S
into two equal subsets S_1
and S_2
, each element in S
also has two choices: either "put in S_1
" or "not put in S_1
(put in S_2
)." The exhaustive approach here is essentially the same as in the knapsack problem.
However, if you want to divide S
into k
equal subsets, it means each element in S
has k
choices, which is fundamentally different from the standard knapsack problem scenario. Therefore, the knapsack problem-solving approach cannot be applied here.