-
Notifications
You must be signed in to change notification settings - Fork 19
/
8.7-Permutations_Without_Dups.py
40 lines (29 loc) · 1.13 KB
/
8.7-Permutations_Without_Dups.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# CTCI 8.7
# Permutations Without Dups
#-------------------------------------------------------------------------------
# My Solution
#-------------------------------------------------------------------------------
def perm(str):
if str == None:
return None
result = []
if len(str) == 0:
result.append("")
return result
first = str[0]
remainder = str[1:len(str)]
# This recursively gets permutations from the remainder, so it starts at the empty string
permutations = perm(remainder)
# For every permutations
for word in permutations:
# For every possible index in each permutation
for i in range(len(word)+1):
# Add the new letter to every index to generate new set of permutations
result.append(insertAt(word, first, i))
return result
def insertAt(str, c, idx):
return str[:idx] + c + str[idx:len(str)]
#-------------------------------------------------------------------------------
#Testing
#-------------------------------------------------------------------------------
print(perm("abcde"))