From 38c43c1c9546b576a5ce76c34bb7db9b60bc39fa Mon Sep 17 00:00:00 2001 From: zongsforce <46927025+zongsforce@users.noreply.github.com> Date: Thu, 23 May 2024 21:44:24 +0800 Subject: [PATCH] modify the sample code the original sample code's complexity is O(n) instead of O(n!) --- .../103-common-runtimes/105-factorial.md | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/data/roadmaps/computer-science/content/103-asymptotic-notation/103-common-runtimes/105-factorial.md b/src/data/roadmaps/computer-science/content/103-asymptotic-notation/103-common-runtimes/105-factorial.md index df4743887..6fd689d37 100644 --- a/src/data/roadmaps/computer-science/content/103-asymptotic-notation/103-common-runtimes/105-factorial.md +++ b/src/data/roadmaps/computer-science/content/103-asymptotic-notation/103-common-runtimes/105-factorial.md @@ -3,9 +3,24 @@ Factorial complexity algorithms have a runtime of `O(n!)`. This is the worst case scenario for an algorithm. Factorial complexity algorithms are very inefficient and should be avoided. ```python -def factorial(n): - if n == 0: - return 1 - else: - return n * factorial(n-1) +def generate_permutations(s): + # Base case: If the string length is 1, return a list containing the string + if len(s) == 1: + return [s] + + # Initialize the result list + permutations = [] + + # Recursively generate all permutations + for i in range(len(s)): + # Current character + current_char = s[i] + # Remaining characters + remaining_chars = s[:i] + s[i+1:] + # Generate all permutations of the remaining characters + for perm in generate_permutations(remaining_chars): + # Add the current character to the front of each generated permutation + permutations.append(current_char + perm) + + return permutations ```