C++_DFS_AC


  • 0
    class Solution {
    public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int res = 0;
        dfs(nums, 0, S, 0, res);
        return res;
    }
    
    bool dfs(vector<int>& nums, int sum, int target, int pos, int& res){
        if(pos == nums.size()){
            if(sum == target) return true;
            return false;
        }
        sum += nums[pos];
        if(dfs(nums, sum, target, pos+1, res)) res++;
        sum -= nums[pos];
        
        sum -=nums[pos];
        if(dfs(nums, sum, target, pos+1, res)) res++;
        sum += nums[pos];
        
        return false;
    }
    };

Log in to reply
 

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