Approach
Depth-first search
For Partition to K Equal Sum Subsets, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 37 lines of C++ from the credited upstream file 698.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool canPartitionKSubsets(vector<int>& nums, int k) {4 const int sum = accumulate(nums.begin(), nums.end(), 0);5 if (sum % k != 0)6 return false;7 8 const int target = sum / k; 9 if (ranges::any_of(nums, [target](const int num) { return num > target; }))10 return false;11 12 ranges::sort(nums, greater<>());13 return dfs(nums, 0, k, 0, target, 0);14 }15 16 private:17 bool dfs(const vector<int>& nums, int s, int remainingGroups, int currSum,18 const int subsetTargetSum, int used) {19 if (remainingGroups == 0)20 return true;21 if (currSum > subsetTargetSum)22 return false;23 if (currSum == subsetTargetSum) 24 return dfs(nums, 0, remainingGroups - 1, 0, subsetTargetSum, used);25 26 for (int i = s; i < nums.size(); ++i) {27 if (used >> i & 1)28 continue;29 if (dfs(nums, i + 1, remainingGroups, currSum + nums[i], subsetTargetSum,30 used | 1 << i))31 return true;32 }33 34 return false;35 }36};37