问题描述:
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,若不能整除k,则直接返回false。若能够整除,则可以进一步检查能否分成这些部分。
可以用dfs来解答。
需要用一个visited数组来记录是否已经用过这个数字。
用k来表示还剩多少部分, start 表示从哪里开始找,target表示目标和,cur_sum表示当前和。
代码:
DFS解法:
class Solution { public: bool canPartitionKSubsets(vector<int>& nums, int k) { if(nums.empty()) return false; int sum = 0; for(int i : nums){ sum += i; } if(sum % k != 0) return false; vector<bool> visited(nums.size(), false); return canPartition(nums, visited, 0, k, 0, sum/k); } bool canPartition(vector<int> &nums, vector<bool> &visited, int start, int k, int cur_sum, int target){ if(k == 1) return true; if(cur_sum == target) return canPartition(nums, visited, 0, k-1, 0, target); for(int i = start; i < nums.size(); i++){ if(!visited[i]){ visited[i] = true; if(canPartition(nums,visited, i+1, k, cur_sum+nums[i], target)) return true; visited[i] = false; } } return false; } };