698. Partition to K Equal Sum Subsets
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
.
class Solution { public: bool canPartitionKSubsets(vector<int>& nums, int k) { //先要知道sum是多少 sum = 0; for (auto it : nums) sum += it; if (sum % k != 0) return false; sum = sum / k; sort(nums.begin(), nums.end(), greater<int>()); for (int i = 0; i < k; i++) group.push_back(0); return helper(nums, 0, group, sum); } bool helper(vector<int>& nums, int i, //当前需要安排第i个 vector<int> group, int all) //每一组的和 { if (i == nums.size()) return true; for (int j = 0; j < group.size(); j++) { if (group[j] + nums[i] <= all) //可以往里面放 { group[j] += nums[i]; if (helper(nums, i + 1, group, all)) return true; group[j] -= nums[i]; } } return false; } private: int sum; vector<int> group; };