Backtracking Algorithm Practice: Partitioning k Subsets
Note
Now all the plugins has supported English. I'm still improving the website...
This article will resolve
LeetCode | Difficulty |
---|---|
698. Partition to K Equal Sum Subsets | 🟠 |
Prerequisites
Before reading this article, you should learn:
I've mentioned before that backtracking is the most useful algorithm for written exams. If you're stuck, use backtracking for a brute-force solution. Even if it doesn't pass all test cases, it can still get you some points. The techniques of backtracking aren't too difficult; it's just the process of exhaustively searching a decision tree. You only need to "make a choice" before recursion and "undo the choice" after recursion.
However, even with brute-force enumeration, different approaches have their pros and cons. In this article, we'll look at a very classic backtracking problem, LeetCode problem #698 "Partition to K Equal Sum Subsets". This problem will help you understand the backtracking mindset more deeply and write backtracking functions with ease.
The problem is quite 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.