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 boolean canPartitionKSubsets(int[] nums, int k) {//mytip //求平均值 if(null==nums||0==nums.length||k<=0){ return false; } int sum=0; for(int i = 0;i<nums.length;i++){ sum+=nums[i]; } if(sum%k!=0){ return false; } boolean[] isVisit=new boolean[nums.length]; return help(nums,isVisit,k,0,sum/k,0); } private boolean help(int[] nums,boolean[] isVisit,int k,int index,int avg,int curSum){ if(k==0){ return true; } if(curSum == avg){ return help(nums,isVisit,k-1,0,avg,0); } for(int i = index;i<nums.length;i++){ if(isVisit[i]){ continue; } isVisit[i] = true; if(avg-curSum>=nums[i]&&help(nums,isVisit,k,i+1,avg,curSum+nums[i])){ return true; } isVisit[i] = false; } return false; } }