1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: unordered_map<string, int> m; int findTargetSumWays(vector<int>& nums, int target) { return dfs(nums, target, 0); } int dfs(vector<int>& nums, int target, int pos) { string key = to_string(target) + "_" + to_string(pos); if (m.count(key)) return m[key]; if (pos == nums.size()) return m[key] = target == 0; return m[key] = dfs(nums, target + nums[pos], pos + 1) + dfs(nums, target - nums[pos], pos + 1); } };
|