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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay