From 7512e773512870bed42887129ae17336bffb2428 Mon Sep 17 00:00:00 2001 From: Neel Date: Mon, 6 Oct 2025 17:00:11 -0400 Subject: [PATCH] Backtracking 2 done --- Problem1.java | 29 +++++++++++++++++++++++++++++ Problem2.java | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 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..8ea139be --- /dev/null +++ b/Problem1.java @@ -0,0 +1,29 @@ +// Time Complexity : O(2^n) *n where n is the size of the input array +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach + +/** + * Using backtracking approach to create a subset at every level with fixed pivot and moving i based for loop. + */ +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..d3a3e0fc --- /dev/null +++ b/Problem2.java @@ -0,0 +1,47 @@ +// Time Complexity : O(2^n) *n where n is the size of the input array +// Space Complexity : O(n^2) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach + +/** + * Backtracking approach with for loop to create a substring at each pivot and i combination. Check if the string is palindrom. + */ +class Solution { + List> result; + + public List> partition(String s) { + this.result = new ArrayList<>(); + backtrack(s, 0, new ArrayList<>(), result); + return result; + } + + private void backtrack(String s, int pivot, List path, List> result) { + if (pivot == s.length()) { + result.add(new ArrayList<>(path)); + return; + } + + for (int i = pivot; i < s.length(); i++) { + String curr = s.substring(pivot, i + 1); + if (isPalindrom(curr)) { + path.add(curr); + backtrack(s, i + 1, path, result); + path.remove(path.size() - 1); + } + } + } + + private boolean isPalindrom(String s) { + int i = 0; + int j = s.length() - 1; + while (i <= j) { + if (s.charAt(i++) != s.charAt(j--)) + return false; + } + + return true; + } +} \ No newline at end of file