My DFS solution in c++


  • 0
    S

    class Solution {
    public:
    int count=0;

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

    };


Log in to reply
 

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