DEV Community

Cover image for Recursion it is : LeetCode 494
Ankit Rattan
Ankit Rattan

Posted on

Recursion it is : LeetCode 494

Today is 26 December, and I found a perfect problem that explains recursion to the point. LeetCode problem 494 is the POTD (Problem of the day). It is named Target Sum, but wait, not the normal generalized target sum that you are thinking right now. It is better to read the problem first and then proceed further here.

So, in this... better to follow your first intuition, that is handling addition (+) and subtraction (-), separately. And when it comes to handle cases individually and combining it in every step we have our BOSS ===> Recursion!

Everytime for each index you are adding and subtracting for each. And at the end when traversing the whole array then, just check if it is equal to the target value or not.

Well, here's the code below. But better you try it first.

*BTW, there is one more approach which I found later, just giving hint : an additional check of even totaling and playing with subsets and maximum value.... okay dp it is! 🫤

    void solve(int& ans, int ind, vector<int>& nums, int sum, int t) {
        if (ind == nums.size()) {
            if (sum == t) {
                ans++;
            }
            return;
        }
        solve(ans, ind + 1, nums, sum + nums[ind], t);
        solve(ans, ind + 1, nums, sum - nums[ind], t);
    }
    int findTargetSumWays(vector<int>& nums, int target) {
        int ans = 0;
        sort(nums.begin(), nums.end());
        int sum = 0;
        int ind = 0;
        solve(ans, ind, nums, sum, target);
        return ans;
    }
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay