알고리즘 공부 2020. 8. 20. 22:25

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

 

Target Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * @param {number[]} nums
 * @param {number} S
 * @return {number}
 */
var map = [];
var findTargetSumWays = function(nums, S) {    
    for( var i=0; i<20; ++i)
        map[i] = [];
    
    var find = function( p_idx, p_sum )  
    {           
        if( p_idx == nums.length )
        {
            if( p_sum == S) return 1;   
            return 0;
        }   
        
        var res =0;
        if( typeof(map[p_idx][p_sum]) != 'undefined' )
            return map[p_idx][p_sum];
        else
        {            
            map[p_idx][p_sum] =find( p_idx+1, p_sum-nums[p_idx] ) + find( p_idx+1, p_sum+nums[p_idx] );
            return map[p_idx][p_sum];
        }
    }    
    return find( 0, 0 );
};
posted by Sense.J
: