diff --git a/Problem-1 b/Problem-1 new file mode 100644 index 00000000..77dd7abf --- /dev/null +++ b/Problem-1 @@ -0,0 +1,28 @@ +// Time Complexity: O(n * 2^n) +// Space Complexity: O(n) + +// Recursively call the function to create the subsets by choosing or not choosing a number +// when choosing a number backtrack to get all subsets +// Add all the subsets to the result list + +class Solution { + public List> subsets(int[] nums) { + List> result = new ArrayList<>(); + helper(nums, 0, result, new ArrayList<>()); + return result; + } + + private void helper(int[] nums, int idx, List> result, List l) { + if(idx == nums.length) { + result.add(new ArrayList<>(l)); + return; + } + + // not choose + helper(nums, idx+1, result, l); + // choose + l.add(nums[idx]); + helper(nums, idx+1, result, l); + l.remove(l.size()-1); + } +} \ No newline at end of file diff --git a/Problem-2 b/Problem-2 new file mode 100644 index 00000000..c4c9aa11 --- /dev/null +++ b/Problem-2 @@ -0,0 +1,43 @@ +// Time complexity: O(n * 2^n) +// Space compexity: O(n^2) + +// Starting from 0 create every substring and check if its a palindrome +// If it is add to list and continue with the remaining string +// When the whole string has been processed add list to the result + +class Solution { + public List> partition(String s) { + List> result = new ArrayList<>(); + helper(s, 0, new ArrayList<>(), result); + return result; + } + + private void helper(String s, int idx, List list, List> result) { + if(idx == s.length()) { + result.add(new ArrayList<>(list)); + return; + } + + for(int i = idx; i < s.length(); i++) { + String sub = s.substring(idx, i+1); + if(isPalindrome(sub)) { + list.add(sub); + helper(s, i+1, list, result); + list.remove(list.size()-1); + } + } + } + + // Function to check if a string is a palindrome + private boolean isPalindrome(String s) { + int l = 0; + int r = s.length()-1; + while(l < r) { + if(s.charAt(l) != s.charAt(r)) + return false; + l++; + r--; + } + return true; + } +} \ No newline at end of file