diff --git a/Parttion.java b/Parttion.java new file mode 100644 index 00000000..64f26dec --- /dev/null +++ b/Parttion.java @@ -0,0 +1,42 @@ +// Time Complexity: O(n * 2^n) +// Space Complexity: O(n) +// Ran on Leetcode succefully: yes +class Solution { + List> ans; + public List> partition(String s) { + ans = new ArrayList<>(); + // start from pivot = 0 + helperPartition(s, 0, new ArrayList<>()); + return ans; + } + + public void helperPartition(String s, int pivot, List curr) { + // if pivot manages to reach the end then the curr is valid + if (pivot == s.length()) { + ans.add(new ArrayList<>(curr)); + return; + } + + for ( int i = pivot; i < s.length(); i++) { + // before adding substring check if it is palindrome; + if(isPalindrome(s.substring(pivot, i + 1))) { + curr.add(s.substring(pivot, i + 1)); + helperPartition(s, i + 1, curr); + curr.remove(curr.size() - 1); + } + } + } + // Check if a string is palindrome + public boolean isPalindrome(String s) { + int L = 0; + int R = s.length() - 1; + // if left and right meet without violating the condition then its a palindrome + while (L < R) { + if(s.charAt(L++) != s.charAt(R--)) { + return false; + } + } + return true; + + } +} \ No newline at end of file diff --git a/Subsets.java b/Subsets.java new file mode 100644 index 00000000..d2108069 --- /dev/null +++ b/Subsets.java @@ -0,0 +1,23 @@ +// Time Complexity: O(n * 2^n) +// Space Complexity: O(n) +// Ran on Leetcode succefully: yes +class Solution { + List> ans; + public List> subsets(int[] nums) { + ans = new ArrayList<>(); + helperSubsets(nums, 0, new ArrayList<>()); + return ans; + } + + public void helperSubsets(int [] nums, int pivot, List list) { + // add deep copy to ans + ans.add(new ArrayList(list)); + for(int i = pivot; i < nums.length; i++) { + list.add(nums[i]); + // explore subsets + helperSubsets(nums, i + 1, list); + // backtrack + list.remove(list.size() - 1); + } + } +} \ No newline at end of file