diff --git a/palindrome-partitioning.py b/palindrome-partitioning.py new file mode 100644 index 00000000..27492979 --- /dev/null +++ b/palindrome-partitioning.py @@ -0,0 +1,29 @@ +''' +Time Complexity: O(n * 2^n) +Space Complexity: O(n) + +Approach: We use backtracking to explore all possible partitions of the string. At each step, we check if the current substring is a palindrome. +If it is, we include it in the current partition and continue exploring further. + If we reach the end of the string, we add the current partition to the result. + +''' + +class Solution: + def partition(self, s: str) -> List[List[str]]: + + path = [] + res = [] + + def solve(start): + if start>=len(s): + res.append(path.copy()) + return + + for i in range(start, len(s)): + if s[start:i+1]==s[start:i+1][::-1]: + path.append(s[start:i+1]) + solve(i+1) + path.pop() + solve(0) + return res + \ No newline at end of file diff --git a/subsets.py b/subsets.py new file mode 100644 index 00000000..cb7efc47 --- /dev/null +++ b/subsets.py @@ -0,0 +1,25 @@ +''' +Time Complexity: O(2^n) +Space Complexity: O(n) + +Approach: We use backtracking to explore all possible subsets of the given list. At each step, we have two choices: either include the current element in the subset or exclude it. We explore both choices recursively and add the resulting subsets to the final result. + +''' +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + N = len(nums) + res = [] + path = [] + def backtrack(index): + if index>=N: + res.append(path.copy()) + return + + backtrack(index+1) + path.append(nums[index]) + backtrack(index+1) + path.pop() + + backtrack(0) + return res +