c++ dfs solution


  • 0
    int findTargetSumWays(vector<int>& nums, int S) 
    {
        int result = 0;
        dfs(nums, 0, S, 0, result);
        
        return result;
    }
    
    void dfs(vector<int>& nums, int sum, int target, int start, int& count)
    {
        if (start >= nums.size())
            return;
        if (start == nums.size() - 1)
        {
            count += (sum + nums[start] == target) + (sum - nums[start] == target);
            return;
        }
        dfs(nums, sum + nums[start], target, start + 1, count);
        dfs(nums, sum - nums[start], target, start + 1, count);
    }

Log in to reply
 

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