Print all possible K | Java program to implement the above approach ; Function to print all subsequences of length K from N natural numbers whose sum equal to N ; Base case ; Iterate over the range [ 1 , N ] ; Insert i into temp ; Pop i from temp ; Utility function to print all subsequences of length K with sum equal to N ; Store all subsequences of length K from N natural numbers ; Store current subsequence of length K from N natural numbers ; Stores total count of subsequences ; Print all subsequences ; Treaverse all subsequences ; Print current subsequence ; If current element is last element of subsequence ; If current subsequence is last subsequence from n natural numbers ; Driver code
import java . io . * ; import java . util . * ; import java . util . stream . Collectors ; class GFG { static void findSub ( List < List < Integer > > res , int sum , int K , int N , List < Integer > temp ) { if ( K == 0 && sum == 0 ) { List < Integer > newList = temp . stream ( ) . collect ( Collectors . toList ( ) ) ; res . add ( newList ) ; return ; } if ( sum <= 0 K <= 0 ) { return ; } for ( int i = 1 ; i <= N ; i ++ ) { temp . add ( i ) ; findSub ( res , sum - i , K - 1 , N , temp ) ; temp . remove ( temp . size ( ) - 1 ) ; } } static void UtilPrintSubsequncesOfKSumN ( int N , int K ) { @ SuppressWarnings ( " unchecked " ) List < List < Integer > > res = new ArrayList ( ) ; @ SuppressWarnings ( " unchecked " ) List < Integer > temp = new ArrayList ( ) ; findSub ( res , N , K , N , temp ) ; int sz = res . size ( ) ; System . out . print ( " { ▁ " ) ; for ( int i = 0 ; i < sz ; i ++ ) { System . out . print ( " { ▁ " ) ; for ( int j = 0 ; j < K ; j ++ ) { if ( j == K - 1 ) System . out . print ( res . get ( i ) . get ( j ) + " ▁ " ) ; else System . out . print ( res . get ( i ) . get ( j ) + " , ▁ " ) ; } if ( i == sz - 1 ) System . out . print ( " } " ) ; else System . out . print ( " } , ▁ " ) ; } System . out . print ( " ▁ } " ) ; } public static void main ( String [ ] args ) { int N = 4 ; int K = 2 ; UtilPrintSubsequncesOfKSumN ( N , K ) ; } }