题目描述:
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.
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.
Note:
- 1 <= k <= len(nums) <= 16.
- 0 < nums[i] < 10000.
题目大意是,给出一串数组。询问是否有可能将其等量分为k份。题目大意很容易理解,思路也比较清晰,搜索。深度优先逐一检查即可。
class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int n = nums.size();
if (k == 1)
return true;
if (n < k)
return false;
int sum = 0;
for (int elem:nums)
sum += elem;
if (sum % k != 0)
return false;
int target = sum / k;
vector<int> subsetSum (k, 0);
vector<bool> taken (n, false);
subsetSum[0] = nums[n-1];
taken[n-1] = true;
return isKPartitionPossibleRec(nums, subsetSum, taken, target, k, n, 0, n-1);
}
bool isKPartitionPossibleRec(vector<int> nums, vector<int> subsetSum, vector<bool> taken,
int target, int k, int n, int curIdx, int limitedIdx) {
if (subsetSum[curIdx] == target) {
if (curIdx == k - 2)
return true;
return isKPartitionPossibleRec(nums, subsetSum, taken, target, k, n, curIdx+1, n-1);
}
for (int i = limitedIdx; i >= 0; i--) {
if (taken[i])
continue;
int tmp = subsetSum[curIdx] + nums[i];
if (tmp <= target) {
taken[i] = true;
subsetSum[curIdx] += nums[i];
bool nxt = isKPartitionPossibleRec(nums, subsetSum, taken,
target, k, n, curIdx, i - 1);
taken[i] = false;
subsetSum[curIdx] -= nums[i];
if (nxt)
return true;
}
}
return false;
}
};