From 03aab4d59581d3c28883bbfff9373c8bf02e5373 Mon Sep 17 00:00:00 2001 From: Indra Date: Tue, 19 May 2026 15:44:05 -0500 Subject: [PATCH] Backtracking 2 Solution --- Problem1.java | 26 ++++++++++++++++++++++++++ Problem2.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 Problem1.java create mode 100644 Problem2.java diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..920f1ec5 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/subsets/ +// Time Complexity : O(2^n) where n is the number of elements in the input array. +// This is because for each element, we have two choices: +// either include it in the subset or exclude it. +// Therefore, the total number of subsets is 2^n. +// Space Complexity : O(2^n) for storing all the subsets. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +class Solution { + public List> subsets(int[] nums) { + List> result = new ArrayList<>(); + helper(nums, 0, new ArrayList<>(), result); + return result; + } + + private void helper(int[] nums, int pivot, List path, List> result){ + result.add(new ArrayList<>(path)); + + for( int i = pivot; i < nums.length; i++){ + path.add(nums[i]); + helper(nums, i+1, path, result); + path.remove(path.size()-1); + } + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..8fac1b1f --- /dev/null +++ b/Problem2.java @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/palindrome-partitioning/ +// Time Complexity : O(n* 2^n) where n is the length of the input string. +// This is because in the worst case, we can have 2^n possible partitions of the string, +// and for each partition, we need to check if it is a palindrome, which takes O(n) time. +// Space Complexity : O(n^ 2) where n is the length of the input string. +// This is because we need to store all possible partitions, +// and each partition can have up to n strings of length up to n. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +class Solution { + public List> partition(String s) { + List> result = new ArrayList<>(); + helper(s, new ArrayList<>(), result); + return result; + } + + private void helper(String s, List path, List> result){ + // base case + if(s.length() == 0){ + result.add(new ArrayList<>(path)); + return; + } + //logic + for(int i = 0; i< s.length(); i++){ + String currStr = s.substring(0, i+1); + if(isPalindrome(currStr)){ + //action + path.add(currStr); + //recurse + helper(s.substring(i+1), path, result); + //backtrack + path.remove(path.size() -1); + } + } + + } + private boolean isPalindrome(String s){ + int i = 0; + int j = s.length() - 1; + while(i