Skip to content

Commit 71394d3

Browse files
authored
Merge pull request #1551 from elcabalero/patch-12
Update target_sum.cpp to match time complexity in C++
2 parents 9ff082c + 84eed62 commit 71394d3

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

cpp/neetcode_150/14_2-d_dynamic_programming/target_sum.cpp

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
Time: O(n x target)
99
Space: O(n x target)
1010
*/
11-
11+
/*
12+
// This solution adds a logn complexity for each insertion and search inside
13+
// of the map (since it is implemented as a tree).
1214
class Solution {
1315
public:
1416
int findTargetSumWays(vector<int>& nums, int target) {
@@ -32,3 +34,33 @@ class Solution {
3234
return dp[{i, total}];
3335
}
3436
};
37+
*/
38+
// Faster solution using a (n x maxSum*2) matrix.
39+
// sumCap is the sum over all the nums array elements, and is
40+
// used both for initializing the array (as an INT_MAX), and
41+
// as an offset to sum to the currSum, in order to match the
42+
// array's 0-indexing (otherwise it would've tried to access the
43+
// -1 element of the array, for example).
44+
// O(n x target) time.
45+
// O(n x maxSum*2) space.
46+
class Solution {
47+
public:
48+
int findTargetSumWays(vector<int>& nums, int target) {
49+
int sumCap = accumulate(nums.begin(), nums.end(), 0) + 1;
50+
vector<vector<int>> DP(nums.size(), vector<int>(sumCap * 2, sumCap));
51+
return backtrack(nums, target, sumCap, 0, 0, DP);
52+
}
53+
private:
54+
int backtrack(vector<int>& nums, int target, int sumCap, int currSum, int idx, vector<vector<int>>& DP){
55+
if (idx == nums.size())
56+
return currSum == target ? 1 : 0;
57+
58+
if (DP[idx][currSum + sumCap] != sumCap)
59+
return DP[idx][currSum + sumCap];
60+
61+
DP[idx][currSum + sumCap] = backtrack(nums, target, sumCap, currSum + nums[idx], idx + 1, DP) +
62+
backtrack(nums, target, sumCap, currSum - nums[idx], idx + 1, DP);
63+
64+
return DP[idx][currSum + sumCap];
65+
}
66+
};

0 commit comments

Comments
 (0)