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