1+ public class K_equal_sum_subset {
2+ //helper function
3+ boolean helpInPartition (int nums [],boolean visited [],int start ,int k ,int currentSum ,int targetSum )
4+ {
5+ //when there are no more subsets left to make
6+ if (k ==0 )
7+ return true ;
8+ if (currentSum >targetSum )
9+ return false ;
10+ //if current sum equals target sum,we are left with k-1 subsets to make
11+ if (currentSum ==targetSum )
12+ return helpInPartition (nums ,visited ,0 ,k -1 ,0 ,targetSum );
13+ for (int j =start ;j <nums .length ;j ++)
14+ {
15+ //if nums[j] is already included in a subset skip this iteration
16+ if (visited [j ])
17+ continue ;
18+ //let us assume nums[j] is a part of the current subset
19+ visited [j ]=true ;
20+ //current sum < target sum,we look for elements beyond j
21+ if (helpInPartition (nums ,visited ,j +1 ,k ,currentSum +nums [j ],targetSum ))
22+ return true ;
23+ //if nums[j] is not a part of the current subset , we mark it unvisited
24+ visited [j ]=false ;
25+ }
26+ return false ;
27+ }
28+ public boolean canPartitionKSubsets (int [] nums , int k ) {
29+ int sum =0 ;
30+ for (int i :nums )
31+ sum +=i ;
32+ //nums can be divided into k equal sum subsets only if the sum of its elements is divisible by k
33+ if (sum %k !=0 )
34+ return false ;
35+ //visited array to keep track where an element is already a part of a subset or not
36+ boolean visited []=new boolean [nums .length ];
37+ return helpInPartition (nums ,visited ,0 ,k ,0 ,sum /k );
38+ }
39+ }
0 commit comments