|
| 1 | +def swap_char(word, i, j): |
| 2 | + swap_index = list(word) |
| 3 | + swap_index[i], swap_index[j] = swap_index[j], swap_index[i] |
| 4 | + return ''.join(swap_index) |
| 5 | + |
| 6 | + |
| 7 | +def permute_string_rec(word, current_index, result): |
| 8 | + if current_index == len(word) - 1: |
| 9 | + result.append(word) |
| 10 | + return |
| 11 | + |
| 12 | + for i in range(current_index, len(word)): |
| 13 | + swapped_str = swap_char(word, current_index, i) |
| 14 | + permute_string_rec(swapped_str, current_index + 1, result) |
| 15 | + |
| 16 | + |
| 17 | +def permute_word(word): |
| 18 | + result = [] |
| 19 | + permute_string_rec(word, 0, result) |
| 20 | + return result |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +# Time Complexity = O(n * n!) |
| 25 | +# Space Complexity = O(n) |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +################################################################# |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +# Driver code |
| 34 | +def main(): |
| 35 | + input_word = ["ab", "bad", "abcd"] |
| 36 | + |
| 37 | + for index in range(len(input_word)): |
| 38 | + permuted_words = permute_word(input_word[index]) |
| 39 | + |
| 40 | + print(index + 1, ".\t Input string: '", input_word[index], "'", sep="") |
| 41 | + print("\t All possible permutations are: ", |
| 42 | + "[", ', '.join(permuted_words), "]", sep="") |
| 43 | + print('-' * 100) |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + main() |
| 48 | + |
| 49 | + |
0 commit comments