Open In App

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

Last Updated : 11 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 = 100
Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44
Explanation: Combinations “111”, “112”, “122”, “124”, “412” are greater than 100. Therefore, these combinations are excluded from the output.

Input: S = “345”, N = 400
Output: 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.
  • After completing the above steps, print the set of all strings stored in combinations[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Store the current sequence of s
string combination;
 
// Store the all the required sequences
set<string> combinations;
 
// Function to print all sequences of S
// satisfying the required condition
void 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 N
void 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 Code
int main()
{
    string S = "124";
    int N = 100;
 
    // Function Call
    generateCombinations(S, N);
 
    // Print required sequences
    printSequences(combinations);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Store the current sequence of s
static String combination = "";
 
// Store the all the required sequences
static HashSet<String> combinations = new LinkedHashSet<String>();
 
// Function to print all sequences of S
// satisfying the required condition
static 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 N
static 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 Code
public 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




# Python3 program for the above approach
 
# Store the current sequence of s
combination = "";
 
# Store the all the required sequences
combinations = [];
 
# Function to print all sequences of S
# satisfying the required condition
def 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 N
def 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 Code
if __name__ == "__main__" :
 
    S = "124";
    N = 100;
 
    # Function Call
    generateCombinations(S, N);
 
    # Print required sequences
    printSequences(combinations);
 
    # This code is contributed by AnkThon


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
// Store the current sequence of s
static String combination = "";
 
// Store the all the required sequences
static SortedSet<String> combinations = new SortedSet<String>();
 
// Function to print all sequences of S
// satisfying the required condition
static 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 N
static 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 Code
public 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


Javascript




<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>


Output: 

1 11 12 14 2 21 22 24 4 41 42 44

 

Time Complexity: O(NN)
Auxiliary Space: O(NN)



Similar Reads

Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K
Given an array a[] consisting of N positive integers, and an integer K, the task is to find the minimum number of operations required to make the sum of adjacent elements less than or equal to K, where, one operation involves decreasing any array element by 1. For every ith element in the given array, the operations can be performed 0 to a[i] times
7 min read
Count N-digit numbers whose digits does not exceed absolute difference of the two previous digits
Given an integer N, the task is to count the number of N-digit numbers such that each digit, except the first and second digits, is less than or equal to the absolute difference of the previous two digits. Examples: Input: N = 1Output: 10Explanation: All the numbers from [0 - 9] are valid because the number of digits is 1. Input : N = 3Output : 375
9 min read
Count maximum elements of an array whose absolute difference does not exceed K
Given an array A and positive integer K. The task is to find maximum number of elements for which the absolute difference of any of the pair does not exceed K.Examples: Input: A[] = {1, 26, 17, 12, 15, 2}, K = 5 Output: 3 There are maximum 3 values so that the absolute difference of each pair does not exceed K(K=5) ie., {12, 15, 17}Input: A[] = {1,
6 min read
Minimum K such that sum of array elements after division by K does not exceed S
Given an array arr[] of N elements and an integer S. The task is to find the minimum number K such that the sum of the array elements does not exceed S after dividing all the elements by K. Note: Consider integer division.Examples: Input: arr[] = {10, 7, 8, 10, 12, 19}, S = 27 Output: 3 After dividing by 3, the array becomes {3, 2, 2, 3, 4, 6} and
11 min read
Count pairs from an array whose quotient of division of larger number by the smaller number does not exceed K
Given an array arr[] of size N, and an integer K, the task is to count the number of pairs from the given array whose quotient of division of the larger element by the smaller element in the pair does not exceed K. Examples: Input: arr[] = {3, 12, 5, 13}, K=2Output: 2Explanation: Pairs satisfying the given conditions are (3, 5) and (12, 13). Input:
10 min read
Maximum value of X such that difference between any array element and X does not exceed K
Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum possible integer X, such that the absolute difference between any array element and X is at most K. If no such value of X exists, then print "-1". Examples: Input: arr[] = {6, 4, 8, 5}, K = 2Output: 6Explanation: Considering X to be 6, t
11 min read
itertools.combinations() module in Python to print all possible combinations
Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2 Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]Recommended: Please try your approach on {IDE} first, before moving on to the solution. This problem has existing recursive solution please refer Print
2 min read
Count subsequences 01 in string generated by concatenation of given numeric string K times
Given a string S and a positive integer K, the task is to find the number of subsequences "01" in the string generated by concatenation of the given numeric string S K times. Examples: Input: S = "0171", K = 2Output: 6Explanation:The string formed by concatenation of S, K number of times is "01710171". There are total 6 possible subsequences which
6 min read
Remove uppercase, lowercase, special, numeric, and non-numeric characters from a String
Given string str of length N, the task is to remove uppercase, lowercase, special, numeric, and non-numeric characters from this string and print the string after the simultaneous modifications. Examples: Input: str = “GFGgfg123$%” Output: After removing uppercase characters: gfg123$% After removing lowercase characters: GFG123$% After removing spe
10 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read