Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Path Sum II #150

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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 03-Arrays/3sum-leetcode.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//Optimized Approach - O(n^2 logn + nlogn) - o(n^2 logn) time and O(n) space
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int target = 0;
sort(nums.begin(), nums.end());
set<vector<int>> s;
vector<vector<int>> output;
for (int i = 0; i < nums.size(); i++){
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) {
s.insert({nums[i], nums[j], nums[k]});
j++;
k--;
} else if (sum < target) {
j++;
} else {
k--;
}
}
}
for(auto triplets : s)
output.push_back(triplets);
return output;
}
};
43 changes: 43 additions & 0 deletions 10- Recursion & Backtracking/Path-Sum-II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:

vector<vector<int>> res; //to store final result

void traverse(TreeNode* root, vector <int> &path, int rem){
if(!root) return; //return at NULL

if(!root->left && !root->right){ //leaf node reached
path.push_back(root->val); //do
if(rem == root->val) res.push_back(path);
//if remaining sum is same as value of root we have valid path
path.pop_back(); // undo
return;
}

int val = root->val; //subtract the contribution of this value from rem (remaining sum)
path.push_back(val); //do
traverse(root->left, path, rem-val); //recurse left subtree
traverse(root->right, path, rem-val); //recurse right subtree
path.pop_back(); //undo

}

vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
res.clear(); //reset res
if(!root) return res; //if root itself NULL there are no paths
vector <int> path; //to store the path
traverse(root, path, targetSum);
return res;
}
};