Target Sum

https://leetcode.com/problems/target-sum/

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        if(nums.size() == 0)
        {
            return 0;
        }

        int result = 0;
        int cur = 0;

        dfs(result, cur, nums, S, 0);

        return result;

    }

    void dfs(int& result, int& cur, vector<int>& nums, int S, int pos)
    {
        if(pos >= nums.size())
        {
            if(cur == S)
            {
                result++;
            }
            return ;
        }

        int org = cur;

        cur = cur+nums[pos];
        dfs(result, cur, nums, S, pos+1);

        cur = cur-nums[pos]*2;
        dfs(result, cur, nums, S, pos+1);

        cur = org;
    }
};

results matching ""

    No results matching ""