Print all possible ways to split an array into K subsets | Java program for above approach ; 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 function ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
import java . util . * ; import java . lang . * ; class Gfg { static void PartitionSub ( int arr [ ] , int i , int N , int K , int nos , ArrayList < ArrayList < Integer > > v ) { if ( i >= N ) { if ( nos == K ) { for ( int x = 0 ; x < v . size ( ) ; x ++ ) { System . out . print ( " { ▁ " ) ; for ( int y = 0 ; y < v . get ( x ) . size ( ) ; y ++ ) { System . out . print ( v . get ( x ) . get ( y ) ) ; if ( y == v . get ( x ) . size ( ) - 1 ) { System . out . print ( " ▁ " ) ; } else { System . out . print ( " , ▁ " ) ; } } if ( x == v . size ( ) - 1 ) { System . out . print ( " } " ) ; } else { System . out . print ( " } , ▁ " ) ; } } System . out . println ( ) ; ; } return ; } for ( int j = 0 ; j < K ; j ++ ) { if ( v . get ( j ) . size ( ) > 0 ) { v . get ( j ) . add ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos , v ) ; v . get ( j ) . remove ( v . get ( j ) . size ( ) - 1 ) ; } else { v . get ( j ) . add ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) ; v . get ( j ) . remove ( v . get ( j ) . size ( ) - 1 ) ; break ; } } } static void partKSubsets ( int arr [ ] , int N , int K ) { ArrayList < ArrayList < Integer > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < K ; i ++ ) v . add ( new ArrayList < > ( ) ) ; if ( K == 0 K > N ) { System . out . println ( " Not ▁ Possible " ) ; } else { System . out . println ( " The ▁ Subset ▁ Combinations ▁ are : ▁ " ) ; PartitionSub ( arr , 0 , N , K , 0 , v ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int K = 2 ; int N = arr . length ; partKSubsets ( arr , N , K ) ; } }