Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions PalindromePartioning.py
Original file line number Diff line number Diff line change
@@ -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

42 changes: 42 additions & 0 deletions subsets.py
Original file line number Diff line number Diff line change
@@ -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