short simple c++ code using hash_map


  • 0
    S
    int findTargetSumWays(vector<int>& nums, int S) 
    {
        unordered_map<int, int> dp_map; //<sum, times>
        dp_map[0] = 1;
        
        for(int i = 0; i < nums.size(); ++i)
        {
            unordered_map<int, int> next_dp_map;
            for(auto & ele : dp_map)
            {
                next_dp_map[ele.first + nums[i]] += ele.second;
                next_dp_map[ele.first - nums[i]] += ele.second;
            }
            dp_map = std::move(next_dp_map);
        }
        
        return dp_map[S];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.