Print all possible ways to split an array into K subsets | Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
function PartitionSub ( arr , i , N , K , nos , v ) { if ( i >= N ) { if ( nos == K ) { for ( let x = 0 ; x < v . length ; x ++ ) { document . write ( " " ) ; for ( let y = 0 ; y < v [ x ] . length ; y ++ ) { document . write ( v [ x ] [ y ] ) ; if ( y == v [ x ] . length - 1 ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } if ( x == v . length - 1 ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } document . write ( " " ) ; } return ; } for ( let j = 0 ; j < K ; j ++ ) { if ( v [ j ] . length > 0 ) { v [ j ] . push ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos , v ) ; v [ j ] . pop ( ) ; } else { v [ j ] . push ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) ; v [ j ] . pop ( ) ; break ; } } } function partKSubsets ( arr , N , K ) { let v = [ ] ; for ( let i = 0 ; i < K ; i ++ ) v . push ( [ ] ) ; if ( K == 0 K > N ) { document . write ( " " + " " ) ; } else { document . write ( " " + " " ) ; PartitionSub ( arr , 0 , N , K , 0 , v ) ; } } let arr = [ 1 , 2 , 3 , 4 ] ; let K = 2 ; let N = arr . length ; partKSubsets ( arr , N , K ) ;