forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain3.cpp
More file actions
50 lines (37 loc) · 1.03 KB
/
main3.cpp
File metadata and controls
50 lines (37 loc) · 1.03 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
/// 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 TreeSet
///
/// Time Complexity: O(n * maxNum * log(n * maxNum))
/// Space Complexity: O(n * maxNum)
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
map<pair<int, int>, int> dp;
return dfs(nums, 0, S, dp);
}
private:
int dfs(const vector<int>& nums, int index, int S,
map<pair<int, int>, int>& dp){
if(index == nums.size())
return S == 0;
pair<int, int> p = make_pair(index, S);
if(dp.count(p))
return dp[p];
int ret = 0;
ret += dfs(nums, index + 1, S - nums[index], dp);
ret += dfs(nums, index + 1, S + nums[index], dp);
return dp[p] = ret;
}
};
int main() {
vector<int> nums = {1, 1, 1, 1, 1};
cout << Solution().findTargetSumWays(nums, 3) << endl;
return 0;
}