My C++ simple DFS solution


  • 0
    W
    class Solution {
    public:
        int findTargetSumWays(vector<int>& nums, int S) {
            return helper(nums,S,0);
        }
        
        int helper(vector<int>& nums, int target, int level){
            if (level == nums.size()){
                if (target==0){
                    return 1;
                }
                return 0;
            }
            int count = 0;
            
            for(int j=0;j<2;j++){
                if (j==0){
                    target -= nums[level];
                    count +=helper(nums,target,level+1);
                    target += nums[level];
                }if (j==1){
                    target += nums[level];
                    count += helper(nums,target,level+1);
                    target -= nums[level];
                }
            } 
            return count;
        }
    };
    

Log in to reply
 

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