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 ; Driver Code ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
def PartitionSub ( arr , i , N , K , nos , v ) : NEW_LINE INDENT if ( i >= N ) : NEW_LINE INDENT if ( nos == K ) : NEW_LINE INDENT for x in range ( len ( v ) ) : NEW_LINE INDENT print ( " { ▁ " , end = " " ) NEW_LINE for y in range ( len ( v [ x ] ) ) : NEW_LINE INDENT print ( v [ x ] [ y ] , end = " " ) NEW_LINE if ( y == len ( v [ x ] ) - 1 ) : NEW_LINE INDENT print ( " ▁ " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT if ( x == len ( v ) - 1 ) : NEW_LINE INDENT print ( " } " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " } , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT return NEW_LINE DEDENT for j in range ( K ) : NEW_LINE INDENT if ( len ( v [ j ] ) > 0 ) : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT def partKSubsets ( arr , N , K ) : NEW_LINE INDENT v = [ [ ] for i in range ( K ) ] NEW_LINE if ( K == 0 or K > N ) : NEW_LINE INDENT print ( " Not ▁ Possible " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ Subset ▁ Combinations ▁ are : ▁ " ) NEW_LINE PartitionSub ( arr , 0 , N , K , 0 , v ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE partKSubsets ( arr , N , K ) NEW_LINE DEDENT