From 0ed77ac36c72c5b16514f63f90dddb4c5bc2561c Mon Sep 17 00:00:00 2001 From: Hemish Veeraboina <85383455+v-hemish@users.noreply.github.com> Date: Tue, 21 Oct 2025 18:24:19 -0400 Subject: [PATCH] Backtracking-2 --- problem1.py | 25 +++++++++++++++++++++++++ problem2.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 problem1.py create mode 100644 problem2.py diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..e953323e --- /dev/null +++ b/problem1.py @@ -0,0 +1,25 @@ +# Space Complexity: O(h) +# Time Complexity: O(2 ^ n) + +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + ans = [] + + def rec(i,res): + if i >= len(nums): + ans.append(res[:]) + return + + + rec(i+1,res) + + res.append(nums[i]) + rec(i+1,res) + res.pop() + + + rec(0,[]) + + return ans + + diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..c205256e --- /dev/null +++ b/problem2.py @@ -0,0 +1,40 @@ +# Space Complexity: O(h) -> h can max to s +# Time Complexity: O(2^n) +class Solution: + def partition(self, s: str) -> List[List[str]]: + def pali(s): + i = 0 + j = len(s)-1 + + while i <= j: + if s[i] != s[j]: + return False + i+=1 + j-=1 + return True + + ans = [] + + def helper(s, pivot, path): + # Base Case + if pivot >= len(s): + ans.append(path[:]) + return + + # Logic + for i in range(pivot, len(s)): + curr = s[pivot:i+1] + if pali(curr): + + #action + path.append(curr) + + #recurse + helper(s, i+1, path) + + #backtrack + path.pop() + + + helper(s, 0, []) + return ans