forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain4.cpp
More file actions
52 lines (38 loc) · 1.1 KB
/
main4.cpp
File metadata and controls
52 lines (38 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/// Source : https://leetcode.com/problems/target-sum/description/
/// Author : liuyubobobo
/// Time : 2018-09-14
#include <iostream>
#include <vector>
#include <map>
using namespace std;
/// Memory Search
/// Using 2D-Array
///
/// Time Complexity: O(n * maxNum)
/// Space Complexity: O(n * maxNum)
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
vector<vector<int>> dp(nums.size(), vector<int>(2001, -1));
return dfs(nums, 0, S, dp);
}
private:
int dfs(const vector<int>& nums, int index, int S,
vector<vector<int>>& dp){
if(index == nums.size())
return S == 0;
if(S + 1000 < 0 || S + 1000 >= 2001)
return 0;
if(dp[index][S + 1000] != -1)
return dp[index][S + 1000];
int ret = 0;
ret += dfs(nums, index + 1, S - nums[index], dp);
ret += dfs(nums, index + 1, S + nums[index], dp);
return dp[index][S + 1000] = ret;
}
};
int main() {
vector<int> nums = {1, 1, 1, 1, 1};
cout << Solution().findTargetSumWays(nums, 3) << endl;
return 0;
}