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
42 changes: 42 additions & 0 deletions PalindromePartitioning.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Time Complexity :O(n* 2^n)
// Space Complexity :O(n^2)
// Did this code successfully run on Leetcode :yes
import java.util.ArrayList;
import java.util.List;

class Solution {
public List<List<String>> partition(String s) {
List<List<String>> answer = new ArrayList<>();
List<String> path = new ArrayList<>();
helper(s, path, answer);
return answer;
}
private void helper(String s, List<String> path, List<List<String>> answer){
if(s.length() == 0){
answer.add(new ArrayList<>(path));
return;
}
for(int i=0; i<s.length(); i++){
String sub = s.substring(0, i+1);
if(isPalindrome(sub)){
//action
path.add(sub);
//recurse
helper(s.substring(i+1), path, answer);
//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;
}
}
56 changes: 56 additions & 0 deletions Subsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Time Complexity :O(n* 2^n)
// Space Complexity :O(n)
// Did this code successfully run on Leetcode :yes

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

class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(nums,0,path,answer);
return answer;
}
private void helper(int nums[],int index,List<Integer> path, List<List<Integer>> answer){
//base
if(index == nums.length){
answer.add(new ArrayList<>(path));
return;
}
//logic
//no choose
helper(nums,index+1,path,answer);
//choose
//action
path.add(nums[index]);
//recurse
helper(nums,index+1,path,answer);
//backtrack
path.remove(path.size()-1);
}
}


// Time Complexity :O(n* 2^n)
// Space Complexity :O(n)
// Did this code successfully run on Leetcode :yes
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
List<Integer> path = new ArrayList<>();
helper(nums,0,path,answer);
return answer;
}
private void helper(int nums[],int pivot,List<Integer> path, List<List<Integer>> answer){
answer.add(new ArrayList<>(path));
for (int i = pivot; i < nums.length; i++) {
// action
path.add(nums[i]);
// recurse
helper(nums, i + 1, path,answer);
// backtrack
path.remove(path.size() - 1);
}
}
}