forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
41 lines (29 loc) · 810 Bytes
/
main.cpp
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
/// Source : https://leetcode.com/problems/target-sum/description/
/// Author : liuyubobobo
/// Time : 2018-09-14
#include <iostream>
#include <vector>
using namespace std;
/// Backtracking
/// Time Complexity: O(2^n)
/// Space Complexity: O(n)
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
return dfs(nums, 0, 0, S);
}
private:
int dfs(const vector<int>& nums, int index, int res, int S){
if(index == nums.size())
return res == S;
int ret = 0;
ret += dfs(nums, index + 1, res - nums[index], S);
ret += dfs(nums, index + 1, res + nums[index], S);
return ret;
}
};
int main() {
vector<int> nums = {1, 1, 1, 1, 1};
cout << Solution().findTargetSumWays(nums, 3) << endl;
return 0;
}