Skip to content

Commit cc4cf3e

Browse files
authored
Generate all subsequences using backtracking (#961)
* Add all_subsequences to backtracking directory
1 parent 1951b4c commit cc4cf3e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

backtracking/all_subsequences.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'''
2+
In this problem, we want to determine all possible subsequences
3+
of the given sequence. We use backtracking to solve this problem.
4+
5+
Time complexity: O(2^n),
6+
where n denotes the length of the given sequence.
7+
'''
8+
9+
10+
def generate_all_subsequences(sequence):
11+
create_state_space_tree(sequence, [], 0)
12+
13+
14+
def create_state_space_tree(sequence, current_subsequence, index):
15+
'''
16+
Creates a state space tree to iterate through each branch using DFS.
17+
We know that each state has exactly two children.
18+
It terminates when it reaches the end of the given sequence.
19+
'''
20+
21+
if index == len(sequence):
22+
print(current_subsequence)
23+
return
24+
25+
create_state_space_tree(sequence, current_subsequence, index + 1)
26+
current_subsequence.append(sequence[index])
27+
create_state_space_tree(sequence, current_subsequence, index + 1)
28+
current_subsequence.pop()
29+
30+
31+
'''
32+
remove the comment to take an input from the user
33+
34+
print("Enter the elements")
35+
sequence = list(map(int, input().split()))
36+
'''
37+
38+
sequence = [3, 1, 2, 4]
39+
generate_all_subsequences(sequence)
40+
41+
sequence = ["A", "B", "C"]
42+
generate_all_subsequences(sequence)

0 commit comments

Comments
 (0)