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

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