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
48 changes: 48 additions & 0 deletions Palindrome Partitioning
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// We’re doing a 0/1 recursion, where at every index we either pick the current substring or skip it.
// If we pick, we check if it's a palindrome and recurse from the next pivot.
// When the full size adds up to the original string, we save that partition.

// time o(2^n * n)
//space o(n^2)

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

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

//no choose
helper(s, pivot, i+1, size, path);

//choose
String subStr = s.substring(pivot, i+1);
if(isPalindrome(subStr)){
//action
path.add(subStr);
//recurse
helper(s, i+1, i+1, size + subStr.length(), path);
//backtrack
path.remove(path.size()-1);
}
}

private boolean isPalindrome(String s){
int left = 0, right = s.length()-1;
while(left < right){
if(s.charAt(left) != s.charAt(right))
return false;
left++; right--;
}
return true;
}
}
24 changes: 24 additions & 0 deletions Subsets
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// We start with the empty subset in the result list.
// For each number, we copy all current subsets and append the number to create new subsets.
// This way, every element doubles the size of the list by being added to existing subsets.

// time o(n * 2^n)
// space o(n)

class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());

for (int i = 0; i < nums.length; i++) {
int size = result.size();
for (int j = 0; j < size; j++) {
List<Integer> temp = new ArrayList<>(result.get(j));
temp.add(nums[i]);
result.add(temp);
}
}

return result;
}
}