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
34 changes: 34 additions & 0 deletions palindromePartition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Time Complexity : O(n * 2^n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Use backtracking. For each index, try every substring s[i:j].
# If the substring is a palindrome, add it to the current partition and
# recursively process the remaining string. When we reach the end of the
# string, store the current partition in the result.



class Solution:
def partition(self, s: str) -> List[List[str]]:
def check_palindrome(i,j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True

def helper(i,arr):
if i == len(s):
res.append(arr[:])
return
for j in range(i,len(s)):
if check_palindrome(i,j):
arr.append(s[i:j + 1])
helper(j + 1,arr)
arr.pop()

res = []
helper(0,[])
return res
26 changes: 26 additions & 0 deletions subSet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Time Complexity : O(n * 2^n)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Use backtracking.
# At each index we have two choices, include the element or exclude it.
# Recursively explore both possibilities and add the subset when we reach
# the end of the array.


class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:

def helper(i,arr):
if i >= len(nums):
self.res.append(arr[:])
return
arr.append(nums[i])
helper(i + 1,arr)
arr.pop()
helper(i + 1,arr)

self.res = []
helper(0,[])
return self.res