Print all n | A C ++ recursive program to print all n - digit numbers whose sum of digits equals to given sum ; n , sum -- > value of inputs out -- > output array index -- > index of next digit to be filled in output array ; Base case ; If number becomes N - digit ; if sum of its digits is equal to given sum , print it ; Traverse through every digit . Note that here we ' re ▁ considering ▁ leading ▁ 0' s as digits ; append current digit to number ; recurse for next digit with reduced sum ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit ; output array to store N - digit numbers ; fill 1 st position by every digit from 1 to 9 and calls findNDigitNumsUtil ( ) for remaining positions ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNDigitNumsUtil ( int n , int sum , char * out , int index ) { if ( index > n sum < 0 ) return ; if ( index == n ) { if ( sum == 0 ) { out [ index ] = ' \0' ; cout << out << " ▁ " ; } return ; } for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = i + '0' ; findNDigitNumsUtil ( n , sum - i , out , index + 1 ) ; } } void findNDigitNums ( int n , int sum ) { char out [ n + 1 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) { out [ 0 ] = i + '0' ; findNDigitNumsUtil ( n , sum - i , out , 1 ) ; } } int main ( ) { int n = 2 , sum = 3 ; findNDigitNums ( n , sum ) ; return 0 ; }