GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Generate all permutations of a sequence, using backtracking (#962) · SharathKumarGithub/Python@839160f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • backtracking
    • all_permutations.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎backtracking/all_permutations.py‎

Copy file name to clipboard
+45Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.