Print all possible K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSub ( vector < vector < int > > & res , int sum , int K , int N , vector < int > & temp ) { if ( K == 0 && sum == 0 ) { res . push_back ( temp ) ; return ; } if ( sum <= 0 K <= 0 ) { return ; } for ( int i = 1 ; i <= N ; i ++ ) { temp . push_back ( i ) ; findSub ( res , sum - i , K - 1 , N , temp ) ; temp . pop_back ( ) ; } } void UtilPrintSubsequncesOfKSumN ( int N , int K ) { vector < vector < int > > res ; vector < int > temp ; findSub ( res , N , K , N , temp ) ; int sz = res . size ( ) ; cout << " { ▁ " ; for ( int i = 0 ; i < sz ; i ++ ) { cout << " { ▁ " ; for ( int j = 0 ; j < K ; j ++ ) { if ( j == K - 1 ) cout << res [ i ] [ j ] << " ▁ " ; else cout << res [ i ] [ j ] << " , ▁ " ; } if ( i == sz - 1 ) cout << " } " ; else cout << " } , ▁ " ; } cout << " ▁ } " ; } int main ( ) { int N = 4 ; int K = 2 ; UtilPrintSubsequncesOfKSumN ( N , K ) ; }