Last active
August 29, 2015 13:56
-
-
Save ta1hia/8929969 to your computer and use it in GitHub Desktop.
Given a string, prints out all possible permutations using a Trie. Solutions for both with and without duplicate characters. Implemented in python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'shawli' | |
#no duplicates | |
class Trie: | |
def __init__(self, ch=""): | |
self.ch = ch #character | |
self.br = [] #branches | |
def addToBranch(self, x): | |
self.br.append(x) | |
def setChar(self, c): | |
self.ch = c | |
def makeTrie(self, s): | |
if not s: | |
return | |
if len(s) == 1: | |
newTrie = Trie(s) | |
self.addToBranch(newTrie) | |
return self | |
for i in range(len(s)): | |
newTrie = Trie(s[i]) | |
rest = s[:i] + s[i+1:] | |
self.addToBranch(newTrie) | |
self.br[-1].makeTrie(rest) | |
def allPerm(self): | |
perms = [] | |
if not self.br: | |
return [self.ch] | |
for i in self.br: | |
for j in i.allPerm(): | |
perms.append(self.ch + j) | |
return perms | |
x = Trie() | |
x.makeTrie("abc") | |
print x.allPerm() | |
print len(x.allPerm()) | |
# > ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] | |
# > 6 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'shawli' | |
#duplicates allowed | |
class Trie: | |
def __init__(self, ch=""): | |
self.ch = ch #character | |
self.br = [] #branches | |
def addToBranch(self, x): | |
self.br.append(x) | |
def setChar(self, c): | |
self.ch = c | |
def makeTrie(self, s): | |
if not s: | |
return | |
"".join(sorted(s)) | |
if len(s) == 1: | |
newTrie = Trie(s) | |
self.setChar(newTrie) | |
return self | |
for i in range(len(s)): | |
if (i == 0) or (s[i-1] is not s[i]): | |
newTrie = Trie(s[i]) | |
rest = s[:i] + s[i+1:] | |
self.addToBranch(newTrie) | |
self.br[-1].makeTrie(rest) | |
def allPerm(self): | |
perms = [] | |
if not self.br: | |
return [self.ch] | |
for i in self.br: | |
for j in i.allPerm(): | |
perms.append(self.ch + j) | |
return perms | |
x = Trie() | |
x.makeTrie("abb") | |
print x.allPerm() | |
print len(x.allPerm()) | |
# > ['abb', 'bab', 'bba'] | |
# > 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment