From e40eb75a57bd2d5ca45431f9fa9cbfc88083c691 Mon Sep 17 00:00:00 2001 From: PrakarshKamal Date: Thu, 12 Mar 2026 21:12:23 -0400 Subject: [PATCH] Complete Backtracking-2 --- PalindromePartitioning.java | 41 +++++++++++++++++++++++++++++++++++++ Subsets.java | 29 ++++++++++++++++++++++++++ 2 files changed, 70 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..ae31e69d --- /dev/null +++ b/PalindromePartitioning.java @@ -0,0 +1,41 @@ +import java.util.*; + +// Backtracking O(n * 2^n) time, O(n) space +class Solution { + List> ans; + public List> partition(String s) { + ans = new ArrayList<>(); + helper(0, s, new ArrayList<>()); + return ans; + } + + private void helper(int idx, String s, List path) { + if (idx == s.length()) { + ans.add(new ArrayList<>(path)); + return; + } + + for (int i = idx; i < s.length(); i++) { + String substring = s.substring(idx, i+1); + if (isPalindrome(substring)) { + path.add(substring); + helper(i+1, s, path); + 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 diff --git a/Subsets.java b/Subsets.java new file mode 100644 index 00000000..e5b8a674 --- /dev/null +++ b/Subsets.java @@ -0,0 +1,29 @@ +import java.util.*; + +// O(n * 2^n) time, O(n) space +class Solution { + List> ans; + + public List> subsets(int[] nums) { + ans = new ArrayList<>(); + helper(0, nums, new ArrayList<>()); + return ans; + } + + private void helper(int idx, int[] nums, List path) { + if (idx == nums.length) { + ans.add(new ArrayList<>(path)); + return; + } + + // choose idx + path.add(nums[idx]); + helper(idx+1, nums, path); + + //backtrack + path.remove(path.size() - 1); + + // dont choose idx + helper(idx+1, nums, path); + } +} \ No newline at end of file