diff --git a/isPalandome.java b/isPalandome.java new file mode 100644 index 00000000..29d2c5a7 --- /dev/null +++ b/isPalandome.java @@ -0,0 +1,46 @@ +// Time Complexity : O(2^n * n) +// Space Complexity : O(n^2) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : None + +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.java b/subsets.java new file mode 100644 index 00000000..d06b3192 --- /dev/null +++ b/subsets.java @@ -0,0 +1,22 @@ +// Time Complexity : O(nx2) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : None + +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; + } +}