diff --git a/Palindrome Partitioning b/Palindrome Partitioning new file mode 100644 index 00000000..fc87657c --- /dev/null +++ b/Palindrome Partitioning @@ -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> result; + public List> 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 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; + } +} diff --git a/Subsets b/Subsets new file mode 100644 index 00000000..301372c6 --- /dev/null +++ b/Subsets @@ -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> subsets(int[] nums) { + List> 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 temp = new ArrayList<>(result.get(j)); + temp.add(nums[i]); + result.add(temp); + } + } + + return result; + } +}