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
28 changes: 28 additions & 0 deletions Problem-1
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Time Complexity: O(n * 2^n)
// Space Complexity: O(n)

// Recursively call the function to create the subsets by choosing or not choosing a number
// when choosing a number backtrack to get all subsets
// Add all the subsets to the result list

class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
helper(nums, 0, result, new ArrayList<>());
return result;
}

private void helper(int[] nums, int idx, List<List<Integer>> result, List<Integer> l) {
if(idx == nums.length) {
result.add(new ArrayList<>(l));
return;
}

// not choose
helper(nums, idx+1, result, l);
// choose
l.add(nums[idx]);
helper(nums, idx+1, result, l);
l.remove(l.size()-1);
}
}
43 changes: 43 additions & 0 deletions Problem-2
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Time complexity: O(n * 2^n)
// Space compexity: O(n^2)

// Starting from 0 create every substring and check if its a palindrome
// If it is add to list and continue with the remaining string
// When the whole string has been processed add list to the result

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

private void helper(String s, int idx, List<String> list, List<List<String>> result) {
if(idx == s.length()) {
result.add(new ArrayList<>(list));
return;
}

for(int i = idx; i < s.length(); i++) {
String sub = s.substring(idx, i+1);
if(isPalindrome(sub)) {
list.add(sub);
helper(s, i+1, list, result);
list.remove(list.size()-1);
}
}
}

// Function to check if a string is a palindrome
private boolean isPalindrome(String s) {
int l = 0;
int r = s.length()-1;
while(l < r) {
if(s.charAt(l) != s.charAt(r))
return false;
l++;
r--;
}
return true;
}
}