From fa9b37e461d3281578bab767efcdd47b82505d52 Mon Sep 17 00:00:00 2001 From: kalyan Date: Thu, 6 Nov 2025 18:46:51 -0600 Subject: [PATCH] Backtracking-2 solutions --- PalindromePartitioning.java | 43 +++++++++++++++++++++++++++++++++++++ Subsets.java | 30 ++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 PalindromePartitioning.java create mode 100644 Subsets.java diff --git a/PalindromePartitioning.java b/PalindromePartitioning.java new file mode 100644 index 00000000..ba1c34c7 --- /dev/null +++ b/PalindromePartitioning.java @@ -0,0 +1,43 @@ +// Time Complexity : O(2^(n) * n) where n is the length of String s. +// Space Complexity : O(n^2) +// Did this code successfully run on Leetcode : Yes +// Approach : I followed for loop recursion with backtracking to get the result. For each substring from pivot to i we each if it is a palindrome and then +// proceed ahead.Once the pivot reaches the end of the string we add it to the result, backtrack it and continue the checks with the rest of the substring. + + +class Solution { + List> result; + public List> partition(String s) { + this.result = new ArrayList<>(); + helper(s, 0, new ArrayList<>()); + return result; + } + + private void helper(String s, int pivot, List path){ + if(pivot == s.length()){ + result.add(new ArrayList<>(path)); + return; + } + + for(int i=pivot; i> result; + public List> subsets(int[] nums) { + this.result = new ArrayList<>(); + helper(nums, 0, new ArrayList<>()); + return result; + } + + private void helper(int[] nums, int index, List path){ + if(index == nums.length){ + result.add(new ArrayList<>(path));//add deep copy to result + return; + } + //don't choose + helper(nums, index+1, path); + + //choose + path.add(nums[index]); + helper(nums, index+1, path);//recurse + path.remove(path.size()-1); //backtrack + } +} \ No newline at end of file