-
Notifications
You must be signed in to change notification settings - Fork 30
/
Partition to K Equal Sum Subsets.cpp
65 lines (47 loc) · 1.48 KB
/
Partition to K Equal Sum Subsets.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Solution by Rahul Surana
***********************************************************
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.
***********************************************************
*/
class Solution {
public:
vector<bool> v;
int ans = 0;
bool df(vector<int>& nums,int i,int sum,int p,int k){
if(k == 1) return true;
if(sum>p) {
// cout << "exceed undone \n";
return false;
}
if(sum == p) {
// cout << "done \n";
return df(nums,0,0,p,k-1);
}
for(int j = i; j < nums.size(); j++){
if(!v[j]){
v[j] = true;
// cout << j <<" k "<< k;
// cout << " s "<<sum+nums[j] <<" -> ";
if(df(nums,j+1,sum+nums[j],p,k)){
return true;
}
v[j] = false;
}
}
// cout << "notdone\n";
return false;
}
bool canPartitionKSubsets(vector<int>& nums, int k) {
int sum = 0;
for(auto x: nums){
sum += x;
}
if(k==0 || sum % k) return false;
int p = sum/k;
cout << p <<"\n";
v.resize(nums.size(),false);
return df(nums,0,0,p,k);;
}
};