1634. [算法课分支限界法]Partition to K Equal Sum Subsets

c++: class Solution { public:

int avg; bool canPartitionKSubsets(vector<int>& nums, int k) { int sum = 0; for(auto p:nums){ sum+=p; } if(sum % k !=0) return false; avg = sum / k; vector<bool> vis(nums.size(),false); return dfs(nums.size()-1,avg,nums,nums.size(),vis); } bool dfs(int start,int target,vector<int> &nums,int remains,vector<bool> &vis){ if(remains==0)return true; bool flag = false; for(int i = start;i >= 0;--i){ if(!vis[i]&&target>=nums[i]){ vis[i]=true; if(target == nums[i])flag = dfs(nums.size()-1,avg,nums,remains-1,vis); else flag = dfs(i-1,target-nums[i],nums,remains-1,vis); if(flag)return flag; vis[i]=false; // while(i>=1&&nums[i]==nums[i-1])i--; } } return flag; }

};