8
8
Time: O(n x target)
9
9
Space: O(n x target)
10
10
*/
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).
12
14
class Solution {
13
15
public:
14
16
int findTargetSumWays(vector<int>& nums, int target) {
@@ -32,3 +34,33 @@ class Solution {
32
34
return dp[{i, total}];
33
35
}
34
36
};
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