diff --git a/PalindromePartitioning.py b/PalindromePartitioning.py new file mode 100644 index 00000000..6c82db6b --- /dev/null +++ b/PalindromePartitioning.py @@ -0,0 +1,35 @@ +# Time Complexity : O(2^n * n) -> For n length string, exponential partitions × (palindrome checks + creating substrings) +# Space Complexity : O(n^2) (substring creation and recursion stack) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : We start at the first index and keep trying all substrings from that point. +# Whenever we find a palindrome substring, we add it and recurse from the next index. +# Once we reach the end, we save the current list, and then backtrack to try other splits. + +class Solution: + def partition(self, s: str) -> List[List[str]]: + self.res = [] + self.helper(s, 0, []) + return self.res + + def helper(self, s, pivot, path): + if pivot == len(s): + self.res.append(list(path)) + return + + for i in range(pivot, len(s)): + subStr = s[pivot:i+1] + if self.isPalindrome(subStr): + path.append(subStr) + self.helper(s, i+1, path) + path.pop() + + def isPalindrome(self, s): + left, right = 0, len(s)-1 + while left < right: + if s[left] != s[right]: + return False + left += 1 + right -= 1 + return True + \ No newline at end of file diff --git a/Subsets.py b/Subsets.py new file mode 100644 index 00000000..8b4e96ad --- /dev/null +++ b/Subsets.py @@ -0,0 +1,22 @@ +# Time Complexity : O(n × 2^n) - 2^n subsets × up-to-n cost to copy path into the result list +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach : We iterate from the current pivot and add each element one by one into the path. +# For every choice, we recurse forward and then backtrack to explore other paths. +# We save a copy of the current list at every level to record all subsets. + +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + self.res = [] + self.path = [] + self.helper(nums, 0) + return self.res + + def helper(self, nums, pivot): + self.res.append(self.path[:]) + for i in range(pivot, len(nums)): + self.path.append(nums[i]) + self.helper(nums, i+1) + self.path.pop() + \ No newline at end of file