Given an integer array nums and an integer k, return true if it is 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.
Example 2:
**Input:** nums = [1,2,3,4], k = 3
**Output:** false
Constraints:
1 <= k <= nums.length <= 16
1 <= nums[i] <= 104
The frequency of each element is in the range [1, 4].
ac1: DFS
classSolution {publicbooleancanPartitionKSubsets(int[] nums,int k) {// edge casesif (nums ==null||nums.length==0|| k <=0||nums.length< k) returnfalse;int sum =0;for (int n : nums) sum += n;if (sum % k !=0) returnfalse;returnhelper(nums,0,newboolean[nums.length],0, sum/k, k-1); } private boolean helper(int[] nums, int startIndex, boolean[] visited, int currSum, int targetSum, int remainSubset) {
// exitif (currSum > targetSum) { // this element not good, find nextreturnfalse; } else if (currSum == targetSum) { // find one subset if (remainSubset == 0) return true; // last subset, since every subset meet target sum, and it has k subset, so return true
elsereturnhelper(nums,0, visited,0, targetSum, remainSubset-1); // go into next subset }// find elements add up to targetSumfor (int i = startIndex; i < nums.length; i++) { // startIndex avoid duplicate, O(2^n)if (visited[i]) continue; visited[i] =true;if (helper(nums, i+1, visited, currSum+nums[i], targetSum, remainSubset)) returntrue; visited[i] =false; }returnfalse; }}