LeetCode 698. Partition to K Equal Sum Subsets 划分为k个相等的子集:典型递归问题
698. Partition to K Equal Sum Subsets 划分为k个相等的子集
题目描述
Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into k non-empty subsets whose sums are all equal.
Note:
1 <= k <= len(nums) <= 16.
0 < nums[i] < 10000.
示例:
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
解答
这道题求的是能否把一个数组中的数,分割成k部分,这k部分的值相等。
对于这种问题,我们可以转化为找到数组的k个子集合,要求每个子集合的值为sum / k, 其中sum是数组值的总和。
然后我们就用递归去找子集合,如果能找到k个子集合就返回true,否则返回false。
递归的时候需要maintain一个visit数组来保存已经访问的点。
代码
class Solution {
vector<int> visit;
int part = 0;
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int sumOfnums = 0;
for (auto & num : nums)
sumOfnums += num;
if (sumOfnums % k) return false;
visit = vector<int>(nums.size(), 0);
part = sumOfnums / k;
return canPartition(nums, k, 0, 0);
}
bool canPartition(vector<int>& nums, int k, int curSum, int start) {
if (k == 0) {
return true;
}
if (curSum > part) return false;
if (curSum == part) {
//cout << k;
return canPartition(nums, k - 1, 0, 0);
}
for (int i = start; i < nums.size(); i ++) {
if (!visit[i]) {
visit[i] = 1;
if(canPartition(nums, k, curSum + nums[i], i + 1)) return true;
visit[i] = 0;
}
}
return false;
}
};