From ed1442c81c0775aa19c951ea545bec85d31a6eb2 Mon Sep 17 00:00:00 2001 From: Serge Mosin Date: Fri, 15 May 2020 18:58:12 +0300 Subject: [PATCH] Permutations solution was added. --- permutations/permutations-serge.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 permutations/permutations-serge.py diff --git a/permutations/permutations-serge.py b/permutations/permutations-serge.py new file mode 100644 index 0000000..df817b1 --- /dev/null +++ b/permutations/permutations-serge.py @@ -0,0 +1,27 @@ +# Backtracking solution +# O(n * n!) time & space complexity + + +def _recursive_permutations(permutation, sequence, picked, result): + if len(picked) == len(sequence): + result.append(permutation) + return + for i, elem in enumerate(sequence): + if i not in picked: + _recursive_permutations(permutation + [elem], sequence, + picked | {i}, result) + + +def get_permutations(s): + result = [] + _recursive_permutations([], s, set(), result) + + return [''.join(permutation) for permutation in result] + + +if __name__ == '__main__': + assert get_permutations('') == [''] + assert get_permutations('a') == ['a'] + assert get_permutations('ab') == ['ab', 'ba'] + assert get_permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] + assert get_permutations('aaa') == ['aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa']