diff --git a/problem1.cpp b/problem1.cpp new file mode 100644 index 00000000..ef2633f8 --- /dev/null +++ b/problem1.cpp @@ -0,0 +1,38 @@ +// Time Complexity : O(2^(m+n)), n = target, m = size of candidates array +// Space Complexity : 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 +// Go over all combinations recursively +// AT every step either pick or no pick the number +// Store all valid combos which result in target sum + +class Solution { +private: + void helper(vector& candidates, int target, int idx, vector& path, vector>& result) { + // base: + if(target < 0 || idx == candidates.size()) { + return; + } + if(target == 0) { + result.push_back(path); + return; + } + // logic: + // pick + path.push_back(candidates[idx]); + helper(candidates, target - candidates[idx], idx, path, result); + path.pop_back(); + // no pick + helper(candidates, target, idx + 1, path, result); + + } +public: + vector> combinationSum(vector& candidates, int target) { + vector> result; + vector path; + helper(candidates, target, 0, path, result); + return result; + } +}; \ No newline at end of file diff --git a/problem2.cpp b/problem2.cpp new file mode 100644 index 00000000..6ba85d12 --- /dev/null +++ b/problem2.cpp @@ -0,0 +1,48 @@ +// Time Complexity : O(4^n) +// Space Complexity : 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: +// Explore all the ways to insert the operators between the digits +// Maintain current total, last number and add to result when expression = target +// Special case: * -> since * has higher precedence, backtrack the last operation +// For *, we backtrack the last addition using tail and recalculate properly because * has higher precedence. + +class Solution { +private: + void helper(string num, int pivot, long calc, long tail, string path, int target, vector& result) { + // base: + if (pivot == num.length()) { + if (calc == target) { + result.push_back(path); + } + return; + } + + // logic: + for (int i = pivot; i < num.length(); i++) { + if (num[pivot] == '0' && i > pivot) break; + + long curr = stol(num.substr(pivot, i - pivot + 1)); + + if (pivot == 0) { + helper(num, i + 1, curr, curr, to_string(curr), target, result); + } else { + // + + helper(num, i + 1, calc + curr, curr, path + "+" + to_string(curr), target, result); + // - + helper(num, i + 1, calc - curr, -curr, path + "-" + to_string(curr), target, result); + // * + helper(num, i + 1, calc - tail + tail * curr, tail * curr, path + "*" + to_string(curr), target, result); + } + } + } + +public: + vector addOperators(string num, int target) { + vector result; + helper(num, 0, 0, 0, "", target, result); + return result; + } +}; \ No newline at end of file