Given an integer array, find all distinct increasing subsequences of length two or more.

For example,

Input: [2, 4, 5, 4]
Output: [[2, 4, 5], [2, 5], [2, 4], [4, 5]]
 
Input: [3, 2, 1]
Output: []

 
We can use backtracking to solve this problem. The idea is to traverse the array from left to right, starting from the next available index, and add the current element to the sequence only if it exceeds the previous element in the sequence. Then recursively explore the remaining elements to check if they will lead to the solution or not. If at any point the sequence has a length of two or more, add it to the result.

 
Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

2 4
2 4 5
2 5
2 4
4 5

Java


Download  Run Code

Output:

[[2, 4], [2, 4, 5], [2, 5], [2, 4], [4, 5]]

Python


Download  Run Code

Output:

[[2, 4], [2, 4, 5], [2, 5], [2, 4], [4, 5]]

 
Note the duplicate subsequences in the output. To generate only distinct subsequences, we can keep track of the processed elements, and proceed only if the current element is not processed before, and more than the previous element in the sequence. The following program demonstrates it in C++, Java, and Python:

C++


Download  Run Code

Output:

2 4
2 4 5
2 5
4 5

Java


Download  Run Code

Output:

[[2, 4], [2, 4, 5], [2, 5], [4, 5]]

Python


Download  Run Code

Output:

[[2, 4], [2, 4, 5], [2, 5], [4, 5]]

 
Here’s alternative solution that avoids the use of set data structure.

C++


Download  Run Code

Output:

2 4 5
2 5
2 4
4 5

Java


Download  Run Code

Output:

[[2, 4, 5], [2, 5], [2, 4], [4, 5]]

Python


Download  Run Code

Output:

[[2, 4, 5], [2, 5], [2, 4], [4, 5]]

The time complexity of all above-discussed methods is exponential and requires additional space for call stack.