From b074ecad1c4275b0387852e669087864cdc288f8 Mon Sep 17 00:00:00 2001 From: dhruvil15 <76967484+dhruvil15@users.noreply.github.com> Date: Thu, 21 May 2026 20:32:59 -0400 Subject: [PATCH] Complete Backtracking-2 --- Problem72.java | 26 ++++++++++++++++++++++++++ Problem73.java | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Problem72.java create mode 100644 Problem73.java diff --git a/Problem72.java b/Problem72.java new file mode 100644 index 00000000..2b7bd235 --- /dev/null +++ b/Problem72.java @@ -0,0 +1,26 @@ +// Time Complexity : O(n × 2ⁿ) - 2ⁿ +// Space Complexity : O(n) + +class Solution { + List> result; + public List> subsets(int[] nums) { + this.result = new ArrayList<>(); + List path = new ArrayList<>(); + helper(nums, 0, path); + return result; + } + + private void helper(int[] nums, int i, List path) { + + if (i == nums.length) { + result.add(new ArrayList<>(path)); + return; + } + + helper(nums, i + 1, path); + + path.add(nums[i]); + helper(nums, i + 1, path); + path.remove(path.size() - 1); + } +} \ No newline at end of file diff --git a/Problem73.java b/Problem73.java new file mode 100644 index 00000000..c5956b32 --- /dev/null +++ b/Problem73.java @@ -0,0 +1,40 @@ +// Time Complexity : O(2^n * n) +// Space Complexity : O(n^2) + +class Solution { + public List> partition(String s) { + List> result = new ArrayList<>(); + helper(s, 0, new ArrayList<>(), result); + return result; + } + + private void helper(String s, int pivot, List path, List> result) { + //base + if(pivot == s.length()) { + result.add(new ArrayList<>(path)); + return; + } + + //logic + for(int i = pivot; i < s.length(); i++) { + String subStr = s.substring(pivot, i+1); + if(isPalindrome(subStr)){ + path.add(subStr); + helper(s, i+1, path, result); + path.remove(path.size()-1); + } + } + } + + private boolean isPalindrome(String s) { + int left = 0; int right = s.length()-1; + while(left < right) { + if(s.charAt(left) != s.charAt(right)) { + return false; + } + left++; right--; + } + + return true; + } +} \ No newline at end of file