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
29 changes: 29 additions & 0 deletions problem1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(n*2^n)
// Space Complexity : O(h) = O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no


// Your code here along with comments explaining your approach
// Start at idx 0 and at every recursive call, add the path to the result
// Start the for loop from the pivot and add the element at idx to path and recurse
// After the recursive call, backtrack the last element added

class Solution {
private:
void helper(vector<int>& nums, int idx, vector<int>& path, vector<vector<int>>& res) {
res.push_back(path);
for(int i=idx; i<nums.size(); i++) {
path.push_back(nums[i]);
helper(nums, i+1, path, res);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> path;
vector<vector<int>> res;
helper(nums, 0, path, res);
return res;
}
};
48 changes: 48 additions & 0 deletions problem2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Time Complexity : O(n*n*2^n)
// Space Complexity : O(n^2)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no


// Your code here along with comments explaining your approach
// start at index 0, break string into substrings at each index
// only if the substring is a palindrome, make a recursive call to process the rest of the string
// backtrack after the recursive call to explore different length substrings
// push the partitions into the result when we reach the end of the string

class Solution {
private:
bool isPal(string str) {
int left = 0;
int right = str.length()-1;
while(left < right) {
if(str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
void helper(string s, int idx, vector<string>& part, vector<vector<string>>& res) {
if(idx == s.length()) {
res.push_back(part);
return;
}
for(int i=idx; i<s.length(); i++) {
string sub = s.substr(idx, i-idx+1);
if(isPal(sub)) {
part.push_back(sub);
helper(s, i+1, part, res);
part.pop_back();
}
}
}
public:
vector<vector<string>> partition(string s) {
vector<string> part;
vector<vector<string>> res;
helper(s, 0, part, res);
return res;
}
};