forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
51 lines (41 loc) · 1.17 KB
/
main2.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
42
43
44
45
46
47
48
49
50
51
/// Source : https://leetcode.com/problems/target-sum/description/
/// Author : liuyubobobo
/// Time : 2018-09-14
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/// Backtracking
/// Using Stack - Non-recursion solution
///
/// Time Complexity: O(2^n)
/// Space Complexity: O(2^n)
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
stack<int> indexStack, sumStack;
indexStack.push(0);
sumStack.push(0);
int res = 0, index, sum;
while(!indexStack.empty()){
index = indexStack.top();
sum = sumStack.top();
indexStack.pop();
sumStack.pop();
if(index + 1 == nums.size())
res += (sum + nums[index] == S) + (sum - nums[index] == S);
else{
indexStack.push(index + 1);
sumStack.push(sum + nums[index]);
indexStack.push(index + 1);
sumStack.push(sum - nums[index]);
}
}
return res;
}
};
int main() {
vector<int> nums = {1, 1, 1, 1, 1};
cout << Solution().findTargetSumWays(nums, 3) << endl;
return 0;
}