Created
March 22, 2016 14:57
-
-
Save netheril96/7c6eb13b7a8cc636e7a6 to your computer and use it in GitHub Desktop.
This file contains 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
from __future__ import print_function | |
# The recursive relation is | |
# f(0) = '' | |
# f(n) = [s + 'a' for s in f(n - 1)] + [s + 'b' for s in f(n - 1)] | |
def allABs1(N): | |
if N <= 0: | |
return [''] | |
res = [] | |
for s in allABs1(N - 1): | |
res.append(s + 'a') | |
res.append(s + 'b') | |
return res | |
# DFS solution, faster and less memory consumption | |
def allABs2(N): | |
res = [] | |
def helper(s): | |
if len(s) == N: | |
res.append(s) | |
else: | |
helper(s + 'a') | |
helper(s + 'b') | |
helper('') | |
return res | |
def test(N): | |
print('All such strings with length ' + str(N)) | |
print('Naive recursion:', allABs1(N)) | |
print('DFS:', allABs2(N)) | |
print() | |
if __name__ == '__main__': | |
for i in range(5): | |
test(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment