From 0cd0da41eafbcb8c1c4f9f85a7f2e732208e1c5c Mon Sep 17 00:00:00 2001 From: pratikb0501 Date: Sat, 16 May 2026 13:34:18 -0700 Subject: [PATCH] Completed Backtracking-2 --- Problem_1.py | 29 +++++++++++++++++++++++++++++ Problem_2.py | 23 +++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 Problem_1.py create mode 100644 Problem_2.py diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 00000000..f3732853 --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,29 @@ +class Solution: + def subsets(self, nums): + result = [] + self.helper(0, nums, [], result) + return result + + def helper(self, pivot, nums, path, result): + result.append(list(path)) + for i in range(pivot, len(nums)): + path.append(nums[i]) + self.helper(i + 1, nums, path, result) + path.pop() + + +# class Solution: +# def subsets(self, nums): +# result = [] +# self.helper(0, nums, [], result) +# return result + +# def helper(self, index, nums, path, result): +# if index == len(nums): +# result.append(list(path)) +# return + +# self.helper(index + 1, nums, path, result) +# path.append(nums[index]) +# self.helper(index + 1, nums, path, result) +# path.pop() \ No newline at end of file diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 00000000..80196549 --- /dev/null +++ b/Problem_2.py @@ -0,0 +1,23 @@ +class Solution: + def partition(self, s): + result = [] + self.helper(0, s, [], result) + return result + + def helper(self, pivot, s, path, result): + if pivot == len(s): + result.append(list(path)) + + for i in range(pivot, len(s)): + if self.isPalindrome(s, pivot, i): + path.append(s[pivot : i + 1]) + self.helper(i + 1, s, path, result) + path.pop() + + def isPalindrome(self, s, i, j): + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True