Print all combinations generated by characters of a numeric string which does not exceed N

11 May, 2021
Given a numeric string S of length M and an integer N, the task is to find all distinct combinations of S (repetitions allowed) that are at most N.
Examples:
Input: S = “124”, N = 100Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44Explanation: Combinations “111”, “112”, “122”, “124”, “412” are greater than 100. Therefore, these combinations are excluded from the output.
Input: S = “345”, N = 400Output: 3, 33, 333, 334, 335, 34, 343, 344, 345, 35, 353, 354, 355, 4, 43, 44, 45, 5, 53, 54, 55
Approach: The idea is to generate all the numbers possible using Backtracking and then print those numbers which does not exceed N. Follow the steps below to solve the problem:
Initialize a Set of strings, say combinations[], to store all distinct combinations of S that numerically does not exceed N.
Initialize a string ans to store the current combination of numbers possible from S.
Declare a function generateCombinations() to generate all required combinations whose values are less than the given value N and the function is defined as:Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations().Backtrack to its previous state by removing the ith character from ans.
Traverse the string S over the range [0, M] using the variable i and do the following:Push the current character S[i] to ans and convert the current string ans to the number and store it in x.If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations().
Push the current character S[i] to ans and convert the current string ans to the number and store it in x.
If x is less than or equal to N then push the string ans into combinations[] and recursively call the function generateCombinations().
Backtrack to its previous state by removing the ith character from ans.
After completing the above steps, print the set of all strings stored in combinations[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Store the current sequence of sstring combination; // Store the all the required sequencesset<string> combinations; // Function to print all sequences of S// satisfying the required conditionvoid printSequences(    set<string> combinations){    // Print all strings in the set    for (string s : combinations) {        cout << s << ' ';    }} // Function to generate all sequences// of string S that are at most Nvoid generateCombinations(string& s, int n){     // Iterate over string s    for (int i = 0; i < s.size(); i++) {         // Push ith character to combination        combination.push_back(s[i]);         // Convert the string to number        long x = stol(combination);         // Check if the condition is true        if (x <= n) {             // Push the current string to            // the final set of sequences            combinations.insert(combination);             // Recursively call function            generateCombinations(s, n);        }         // Backtrack to its previous state        combination.pop_back();    }} // Driver Codeint main(){    string S = "124";    int N = 100;     // Function Call    generateCombinations(S, N);     // Print required sequences    printSequences(combinations);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Store the current sequence of sstatic String combination = ""; // Store the all the required sequencesstatic HashSet<String> combinations = new LinkedHashSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences(    HashSet<String> combinations){         // Print all Strings in the set    for(String s : combinations)    {        System.out.print(s + " ");    }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){         // Iterate over String s    for(int i = 0; i < s.length(); i++)    {                 // Push ith character to combination        combination += (s.charAt(i));         // Convert the String to number        long x = Integer.valueOf(combination);         // Check if the condition is true        if (x <= n)        {                         // Push the current String to            // the final set of sequences            combinations.add(combination);             // Recursively call function            generateCombinations(s, n);        }         // Backtrack to its previous state        combination = combination.substring(            0, combination.length() - 1);    }} // Driver Codepublic static void main(String[] args){    String S = "124";    int N = 100;         // Function Call    generateCombinations(S, N);     // Print required sequences    printSequences(combinations);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Store the current sequence of scombination = ""; # Store the all the required sequencescombinations = []; # Function to print all sequences of S# satisfying the required conditiondef printSequences(combinations) :         # Print all strings in the set    for s in (combinations) :        print(s, end = ' ');  # Function to generate all sequences# of string S that are at most Ndef generateCombinations(s, n) :       global combination;     # Iterate over string s    for i in range(len(s)) :         # Push ith character to combination        combination += s[i];         # Convert the string to number        x = int(combination);         # Check if the condition is true        if (x <= n) :             # Push the current string to            # the final set of sequences            combinations.append(combination);             # Recursively call function            generateCombinations(s, n);         # Backtrack to its previous state        combination = combination[:-1]; # Driver Codeif __name__ == "__main__" :     S = "124";    N = 100;     # Function Call    generateCombinations(S, N);     # Print required sequences    printSequences(combinations);     # This code is contributed by AnkThon
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Store the current sequence of sstatic String combination = ""; // Store the all the required sequencesstatic SortedSet<String> combinations = new SortedSet<String>(); // Function to print all sequences of S// satisfying the required conditionstatic void printSequences(    SortedSet<String> combinations){         // Print all Strings in the set    foreach(String s in combinations)    {        Console.Write(s + " ");    }} // Function to generate all sequences// of String S that are at most Nstatic void generateCombinations(String s, int n){         // Iterate over String s    for(int i = 0; i < s.Length; i++)    {                 // Push ith character to combination        combination += (s[i]);         // Convert the String to number        long x = Int32.Parse(combination);         // Check if the condition is true        if (x <= n)        {                         // Push the current String to            // the readonly set of sequences            combinations.Add(combination);             // Recursively call function            generateCombinations(s, n);        }         // Backtrack to its previous state        combination = combination.Substring(            0, combination.Length - 1);    }} // Driver Codepublic static void Main(String[] args){    String S = "124";    int N = 100;         // Function Call    generateCombinations(S, N);     // Print required sequences    printSequences(combinations);}} // This code is contributed by 29AjayKumar
<script>      // JavaScript program for the above approach      // Store the current sequence of s      var combination = "";       // Store the all the required sequences      var combinations = [];       // Function to print all sequences of S      // satisfying the required condition      function printSequences(combinations) {        // Print all Strings in the set        for (var s of combinations) {          document.write(s + " ");        }      }       // Function to generate all sequences      // of String S that are at most N      function generateCombinations(s, n) {        // Iterate over String s        for (var i = 0; i < s.length; i++) {          // Push ith character to combination          combination += s[i];           // Convert the String to number          var x = parseInt(combination);           // Check if the condition is true          if (x <= n) {            // Push the current String to            // the readonly set of sequences            combinations.push(combination);             // Recursively call function            generateCombinations(s, n);          }           // Backtrack to its previous state          combination = combination.substring(0, combination.length - 1);        }      }       // Driver Code      var S = "124";      var N = 100;       // Function Call      generateCombinations(S, N);       // Print required sequences      printSequences(combinations);    </script>
1 11 12 14 2 21 22 24 4 41 42 44
 
Time Complexity: O(NN)Auxiliary Space: O(NN)
amit143katiyar
ankthon
khushboogoyal499
29AjayKumar
rdtank
Permutation and Combination
Backtracking
Mathematical
Recursion
Strings
Strings
Mathematical
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Backtracking to find all subsets
Printing all solutions in N-Queen Problem
Generate all the binary strings of N bits
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7