494. Target Sum

class Solution {
public:
    unordered_map<string, int> dp;
    int findTargetSumWays(vector<int>& nums, int S) {
        return helper(nums, S, 0);
    }
    int helper(vector<int>& nums, int S, int start) {
        string key = to_string(S) + ":" + to_string(start);
        if (dp.find(key) != dp.end())
            return dp[key];
        if (start == nums.size()) {
            return S == 0;
        }
        int res = helper(nums, S-nums[start], start+1) +
            helper(nums, S+nums[start], start+1);
        return dp[key] = res;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/9105077.html