diff --git a/PalindromePartioning.py b/PalindromePartioning.py new file mode 100644 index 00000000..d72540ad --- /dev/null +++ b/PalindromePartioning.py @@ -0,0 +1,39 @@ +# Time Complexity : O(n. 2^n) +# Space Complexity : O(n^2) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# The approach here to do a backtrack using the iterative for loop approach. But before continuing the recursion, check if the +# substring is a palindrome or not. + +class Solution: + def partition(self, s: str) -> List[List[str]]: + result = [] + + def backtrack(pivot, path): + # Base case + if pivot == len(s): + result.append(path.copy()) + return + # Logic + for i in range(pivot, len(s)): + subString = s[pivot: i + 1] + if isPalindrome(subString): + path.append(subString) + backtrack(i + 1, path) + path.pop() + + def isPalindrome(currStr): + p1 = 0 + p2 = len(currStr) - 1 + + while (p1 <= p2): + if currStr[p1] != currStr[p2]: + return False + p1 += 1 + p2 -= 1 + return True + + backtrack(0, []) + return result + diff --git a/subsets.py b/subsets.py new file mode 100644 index 00000000..60a79f95 --- /dev/null +++ b/subsets.py @@ -0,0 +1,42 @@ +# Time Complexity : O(2^n) +# Space Complexity : O(n^2) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# The approach here to do a backtrack either using 01 approach(choose, not choose) or using the iterative for loop approach to +# get all the subsets. + +class Solution: + def subsets01Recursion(self, nums: List[int]) -> List[List[int]]: + result = [] + + def helper(path, idx): + if idx == len(nums): + result.append(path.copy()) + return + + helper(path, idx + 1) + path.append(nums[idx]) + helper(path, idx + 1) + path.pop() + + helper([], 0) + + return result + + +class Solution: + def subsetsIterativeRecursion(self, nums: List[int]) -> List[List[int]]: + result = [] + + def helper(path, pivot): + result.append(path.copy()) + for i in range(pivot, len(nums)): + path.append(nums[i]) + helper(path, i + 1) + path.pop() + + helper([], 0) + + return result +