Combinations in a String of Digits

06 May, 2021
Given an input string of numbers, find all combinations of numbers that can be formed using digits in the same order.Examples: 
Input : 123 
Output :1 2 3
        1 23
        12 3
        123

Input : 1234
Output : 1 2 3 4 
        1 2 34 
        1 23 4 
        1 234 
        12 3 4 
        12 34 
        123 4 
        1234 
The problem can be solved using recursion. We keep track of the current index in the given input string and the length of the output string so far. In each call to the function, if there are no digits remaining in the input string print the current output string and return. Otherwise, copy the current digit to output. From here make two calls, one considering the next digit as part of the next number(including a space in output string) and one considering the next digit as part of the current number( no space included). If there are no digits remaining after the current digit the second call to the function is omitted because a trailing space doesn’t count as a new combination. 
C++
Java
Python3
C#
Javascript
// CPP program to find all combination of numbers// from a given string of digits#include <iostream>#include <cstring>using namespace std; // function to print combinations of numbers// in given input stringvoid printCombinations(char* input, int index,                     char* output, int outLength){    // no more digits left in input string    if (input[index] == '\0')    {        // print output string & return        output[outLength] = '\0';        cout << output << endl;        return;    }         // place current digit in input string    output[outLength] = input[index];         // separate next digit with a space    output[outLength + 1] = ' ';         printCombinations(input, index + 1, output,                                   outLength + 2);         // if next digit exists make a    // call without including space    if(input[index + 1] != '\0')    printCombinations(input, index + 1, output,                                    outLength + 1);     } // driver function to test above functionint main(){    char input[] = "1214";    char *output = new char[100];     // initialize output with empty string    output[0] = '\0';         printCombinations(input, 0, output, 0);    return 0;}
// Java program to find all combinations// of numbers from a given string of digitsclass GFG{     // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input,                              int index,                              char[] output,                              int outLength){    // no more digits left in input string    if (input.length == index)    {        // print output string & return        System.out.println(String.valueOf(output));        return;    }         // place current digit in input string    output[outLength] = input[index];         // separate next digit with a space    output[outLength + 1] = ' ';         printCombinations(input, index + 1, output,                                outLength + 2);         // if next digit exists make a    // call without including space    if(input.length!=index + 1)    printCombinations(input, index + 1, output,                                outLength + 1);} // Driver Codepublic static void main(String[] args){    char input[] = "1214".toCharArray();    char []output = new char[100];         printCombinations(input, 0, output, 0);}} // This code is contributed by Rajput-Ji
# Python3 program to find all combination of numbers# from a given string of digits # function to print combinations of numbers# in given input stringdef printCombinations(input, index, output, outLength):         # no more digits left in input string    if (len(input) == index):                 # print output string & return        output[outLength] = '\0'        print(*output[:outLength], sep = "")        return         # place current digit in input string    output[outLength] = input[index]         # separate next digit with a space    output[outLength + 1] = ' '    printCombinations(input, index + 1,                       output, outLength + 2)         # if next digit exists make a    # call without including space    if(len(input) != (index + 1)):        printCombinations(input, index + 1,                          output, outLength + 1) # Driver codeinput = "1214"output = [0]*100 # initialize output with empty stringoutput[0] = '\0' printCombinations(input, 0, output, 0) # This code is contributed by SHUBHAMSINGH10
// C# program to find all combinations// of numbers from a given string of digitsusing System;     class GFG{     // function to print combinations of numbers// in given input stringstatic void printCombinations(char[] input,                              int index,                              char[] output,                              int outLength){    // no more digits left in input string    if (input.Length == index)    {        // print output string & return        Console.WriteLine(String.Join("",                                output));        return;    }         // place current digit in input string    output[outLength] = input[index];         // separate next digit with a space    output[outLength + 1] = ' ';         printCombinations(input, index + 1, output,                                outLength + 2);         // if next digit exists make a    // call without including space    if(input.Length!=index + 1)    printCombinations(input, index + 1, output,                                outLength + 1);} // Driver Codepublic static void Main(String[] args){    char []input = "1214".ToCharArray();    char []output = new char[100];         printCombinations(input, 0, output, 0);}} // This code is contributed by 29AjayKumar
<script>// Javascript program to find all combinations// of numbers from a given string of digits     // function to print combinations of numbers// in given input string    function printCombinations(input,index,output,outLength)    {             // no more digits left in input string    if (input.length == index)    {             // print output string & return        document.write(output.join("")+"<br>");        return;    }          // place current digit in input string    output[outLength] = input[index];          // separate next digit with a space    output[outLength + 1] = ' ';          printCombinations(input, index + 1, output,                                outLength + 2);          // if next digit exists make a    // call without including space    if(input.length != index + 1)    printCombinations(input, index + 1, output,                                outLength + 1);    }         // Driver Code    let input = "1214".split("");    let output = new Array(100);    printCombinations(input, 0, output, 0);         // This code is contributed by avanitrachhadiya2155</script>
Output:  
1 2 1 4
1 2 14
1 21 4
1 214
12 1 4
12 14
121 4
1214
Alternative Solution:  
C++
Java
Python3
C#
Javascript
// CPP program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string#include <bits/stdc++.h>using namespace std; // function to print combinations of// numbers in given input stringvoid printCombinations(char s[]){         // find length of char array    int l = strlen(s);     // we can give space between characters    // ex. ('1' & '2') or ('2' & '3') or    // ('3' & '4') or ('3' & '4') or all    // that`s why here we have maximum    // space length - 1    for(int i = 0; i < pow(2, l - 1); i++){        int k = i, x = 0;                 // first character will be printed        // as well        cout << s[x];        x++;        for(int j = 0; j < strlen(s) - 1; j++){                         // if bit is set, means provide            // space            if(k & 1)                cout << " ";            k = k >> 1;            cout << s[x];                         // always increment index of            // input string            x++;        }        cout << "\n";    }} // driver codeint main() {     char input[] = "1214";    printCombinations(input);         return 0;}// This code is contributed by PRINCE Gupta 2
// Java program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringimport java.util.*; class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char s[]){         // find length of char array    int l = s.length;     // we can give space between characters    // ex. ('1' & '2') or ('2' & '3') or    // ('3' & '4') or ('3' & '4') or all    // that`s why here we have maximum    // space length - 1    for(int i = 0;            i < Math.pow(2, l - 1); i++)    {        int k = i, x = 0;                 // first character will be printed        // as well        System.out.print(s[x]);        x++;        for(int j = 0;                j < s.length - 1; j++)        {                         // if bit is set, means provide            // space            if(k % 2 == 1)                System.out.print(" ");            k = k >> 1;            System.out.print(s[x]);                         // always increment index of            // input string            x++;        }        System.out.print("\n");    }} // Driver Codepublic static void main(String[] args){    char input[] = "1214".toCharArray();    printCombinations(input);}} // This code is contributed by PrinciRaj1992
# Python 3 program to find all# combination of numbers from# a given string of digits using# bit algorithm used same logic# as to print power set of string # Function to print combinations of# numbers in given input stringdef printCombinations(s):         # find length of char array    l = len(s);     # we can give space between    # characters ex. ('1' & '2')    # or ('2' & '3') or ('3' & '4')    # or ('3' & '4') or all that`s    # why here we have maximum    # space length - 1    for i in range(pow(2, l - 1)):        k = i        x = 0                 # first character will        # be printed as well        print(s[x], end = "")        x += 1                 for j in range(len(s) - 1):                         # if bit is set, means            # provide space            if(k & 1):                print(" ", end = "")            k = k >> 1            print(s[x], end = "")                         # always increment index of            # input string            x += 1                 print() # Driver codeif __name__ == "__main__":     inp = "1214";    printCombinations(inp); # This code is contributed by Chitranayal
// C# program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of stringusing System;     class GFG{ // function to print combinations of// numbers in given input stringstatic void printCombinations(char []s){         // find length of char array    int l = s.Length;     // we can give space between characters    // ex. ('1' & '2') or ('2' & '3') or    // ('3' & '4') or ('3' & '4') or all    // that`s why here we have maximum    // space length - 1    for(int i = 0;            i < Math.Pow(2, l - 1); i++)    {        int k = i, x = 0;                 // first character will be printed        // as well        Console.Write(s[x]);        x++;        for(int j = 0;                j < s.Length - 1; j++)        {                         // if bit is set, means provide            // space            if(k % 2 == 1)                Console.Write(" ");            k = k >> 1;            Console.Write(s[x]);                         // always increment index of            // input string            x++;        }        Console.Write("\n");    }} // Driver Codepublic static void Main(String[] args){    char []input = "1214".ToCharArray();    printCombinations(input);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to find all combination of// numbers from a given string of digits// using bit algorithm used same logic// as to print power set of string         // function to print combinations of    // numbers in given input string    function printCombinations(s)    {        // find length of char array    let l = s.length;      // we can give space between characters    // ex. ('1' & '2') or ('2' & '3') or    // ('3' & '4') or ('3' & '4') or all    // that`s why here we have maximum    // space length - 1    for(let i = 0;            i < Math.pow(2, l - 1); i++)    {        let k = i, x = 0;                  // first character will be printed        // as well        document.write(s[x]);        x++;        for(let j = 0;                j < s.length - 1; j++)        {                          // if bit is set, means provide            // space            if(k % 2 == 1)                document.write(" ");            k = k >> 1;            document.write(s[x]);                          // always increment index of            // input string            x++;        }        document.write("<br>");    }    }         // Driver Code    let input= "1214".split("");    printCombinations(input);         // This code is contributed by rag2127     </script>
Output:  
1214
1 214
12 14
1 2 14
121 4
1 21 4
12 1 4
1 2 1 4
This article is contributed by aditi sharma 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Chaitanya Tyagi
princiraj1992
Rajput-Ji
29AjayKumar
SHUBHAMSINGH10
ukasp
avanitrachhadiya2155
rag2127
Combinatorial
Recursion
Recursion
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Combinational Sum
Find the K-th Permutation Sequence of first N natural numbers
Count ways to reach the nth stair using step 1, 2 or 3
Count Derangements (Permutation such that no element appears in its original position)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Print all subsequences of a string