problem
solution
- backtracking
O(2^N)
time1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution {
public:
vector<string> ret;
void backtracking(vector<int>& nums, int i,string path, int sum, int target){
if(i==nums.size()){
if(sum == target) ret.push_back(path);
return;
}
backtracking(nums, i+1, path+"+"+to_string(nums[i]), sum+nums[i], target);
backtracking(nums, i+1, path+"-"+to_string(nums[i]), sum-nums[i], target);
}
int findTargetSumWays(vector<int>& nums, int target) {
int n = nums.size();
string path;
backtracking(nums, 0, path,0, target);
return ret.size();
}
};
option 1 - backtracking
1 | class Solution { |
option 2 - memo pattern
1 | class Solution { |