Skip to content

Commit 5907dc5

Browse files
authored
Merge pull request kothariji#544 from poojaagrawal134/master
Code to Leetcode Problem Partition_to_K_Equal_Sum_Subsets
2 parents c864006 + e0dc4b8 commit 5907dc5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
bool canPartitionKSubsets(vector<int>& nums, int k) {
4+
int total = accumulate(nums.begin(), nums.end(), 0);
5+
if (total % k) return false;
6+
int avg = total / k;
7+
8+
vector<int> sm(k);
9+
sort(nums.begin(), nums.end(), [&](auto& lhs, auto& rhs) {return lhs > rhs; });
10+
11+
function<bool(int)> fn = [&](int i) {
12+
if (i == nums.size()) return true;
13+
for (int kk = 0; kk < k; ++kk) {
14+
if (sm[kk] + nums[i] <= avg) {
15+
sm[kk] += nums[i];
16+
if (fn(i+1)) return true;
17+
sm[kk] -= nums[i];
18+
}
19+
if (sm[kk] == 0) break;
20+
}
21+
return false;
22+
};
23+
24+
return fn(0);
25+
}
26+
};

0 commit comments

Comments
 (0)