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
41 changes: 41 additions & 0 deletions PalindromePartitioning.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.*;

// Backtracking O(n * 2^n) time, O(n) space
class Solution {
List<List<String>> ans;
public List<List<String>> partition(String s) {
ans = new ArrayList<>();
helper(0, s, new ArrayList<>());
return ans;
}

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

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

private boolean isPalindrome(String s) {
int left = 0;
int right = s.length()-1;

while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
29 changes: 29 additions & 0 deletions Subsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.*;

// O(n * 2^n) time, O(n) space
class Solution {
List<List<Integer>> ans;

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

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

// choose idx
path.add(nums[idx]);
helper(idx+1, nums, path);

//backtrack
path.remove(path.size() - 1);

// dont choose idx
helper(idx+1, nums, path);
}
}