Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//TC - O(2^n)
//SC - O(N)

/*
The subsets method initializes the result list and starts backtracking from index 0 with an empty subset.
The backtrack method adds the current subset to the result and recursively explores all choices by including each element from the current index onward.
After each recursive call, the last added element is removed to backtrack and generate the remaining subsets.
*/


import java.util.ArrayList;
import java.util.List;

public class Problem1 {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, res, new ArrayList<Integer>(), 0);
return res;
}

private void backtrack(int[] nums, List<List<Integer>> res, List<Integer> temp, int pivot) {
res.add(new ArrayList<>(temp));

//logic
for(int i = pivot;i<nums.length;i++) {
//action
temp.add(nums[i]);
//recurse
backtrack(nums,res, temp, i+1);
//backtrack
temp.remove(temp.size()-1);
}
}
}
55 changes: 55 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//TC - O(n.2^n)
//SC - O(N)

/*
The code uses backtracking to generate all possible palindrome partitions of the string starting from a given index (pivot).
At each step, it tries every possible substring from pivot onward and recurses only if the substring is a palindrome.
When the end of the string is reached, the current partition is added to the result, and backtracking removes the last substring to explore other partitions.
*/

import java.util.ArrayList;
import java.util.List;

public class Problem2 {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
helper(s, res, new ArrayList<>(), 0);
return res;
}

private void helper(String s, List<List<String>> res, List<String> temp, int pivot) {
//base
if(pivot == s.length()) {
res.add(new ArrayList<>(temp));
return;
}
//logic
for(int i = pivot;i<s.length();i++) {
if(isPalindrome(pivot, i, s)) {
//action
temp.add(s.substring(pivot, i+1));
//recurse
helper(s, res, temp, i+1);
//backtrack
temp.remove(temp.size()-1);
}

//action
//recurse

//backtrack
}
}

private boolean isPalindrome(int start, int end, String s) {
while(start <= end) {
if(s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}

return true;
}
}