From f02afdfa42a7994e66e3d70a816ec4fa0884d38c Mon Sep 17 00:00:00 2001 From: Botla Date: Sat, 20 Dec 2025 14:52:01 -0700 Subject: [PATCH] Backtracking-2 --- PalindromePartitioning_131.py | 44 +++++++++++++++++++++++++++++++++++ Subsets_78.py | 38 ++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 PalindromePartitioning_131.py create mode 100644 Subsets_78.py diff --git a/PalindromePartitioning_131.py b/PalindromePartitioning_131.py new file mode 100644 index 00000000..71c74ddc --- /dev/null +++ b/PalindromePartitioning_131.py @@ -0,0 +1,44 @@ +# Time Complexity : It is O(n) since we are iterating with the list. +# Space Complexity : It is O(n) we can insert all elements in the queue if value is 1. +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : + +from typing import List +import copy + +class Solution: + def partition(self, s: str) -> List[List[str]]: + permutation=[] + result=[] + Solution.calPermutation(s,0,permutation,result) + return result + + def calPermutation(s: str, pivot:int, permutation:[],result:[]): + if len(s)==pivot: + result.append(permutation) + return + #permutation.append(s[pivot]) + for i in range(pivot,len(s)): + updatedStr = s[pivot:i+1] + #action + if(updatedStr != '' and Solution.isPalindrome(updatedStr)): + permutation.append(updatedStr) + #recurse + Solution.calPermutation(s,i+1,copy.deepcopy( permutation),result) + #Solution.calPermutation(s,i+1,permutation,result) + + #backtrack + permutation.pop() + + def isPalindrome(palStr: str)-> bool: + lenStr = len(palStr)//2 + for i in range(lenStr): + if palStr[i] != palStr[(len(palStr)-1)-i]: + return False + return True + + + +obj = Solution() +#print(obj.partition("abcba")) +print(obj.partition("aaba")) \ No newline at end of file diff --git a/Subsets_78.py b/Subsets_78.py new file mode 100644 index 00000000..b041169b --- /dev/null +++ b/Subsets_78.py @@ -0,0 +1,38 @@ +# Time Complexity : It is O(n) since we are iterating with the list. +# Space Complexity : It is O(n) we can insert all elements in the queue if value is 1. +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : + +from typing import List +import copy + +class Solution: + + def subsets(self, nums: List[int]) -> List[List[int]]: + path = [] + result = [] + Solution.calSubSet(nums,0,path,result) + return result + + def calSubSet(nums: List[int],i : int,path: [],result:[]): + + listLen = len(nums) + if listLen == i: + result.append(path) + return + + #NotChose + Solution.calSubSet(nums,i+1, copy.deepcopy(path),result) + #Chose + path.append(nums[i]) + Solution.calSubSet(nums,i+1,copy.deepcopy(path),result) + return + #return Solution.result + +obj = Solution() +print(obj.subsets([0])) +print(obj.subsets([1,2,3])) +print(obj.subsets([3,2,4,1])) +print(obj.subsets([0])) +# print(obj.subsets([1,2])) +