![]() |
VOOZH | about |
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.
Output:
1 2 1 4
1 2 14
1 21 4
1 214
12 1 4
12 14
121 4
1214
Time complexity : O(2^n)
Space complexity : O(n^2)
Alternative Solution:
Output:
1214
1 214
12 14
1 2 14
121 4
1 21 4
12 1 4
1 2 1 4
Time Complexity : O(n * 2^n)
Space Complexity : O(n)