mystry :same complexity passes and fails ::


  • 0
    M

    :)
    following code fails (TLE) but the lower code passes

    class Solution 
    {
        int recurse(vector<int> nums,int i,long long int sum,long long int S,int c)
        {
            if((i==(nums.size()))&&(sum==S))
            {
                c++;
            }
            else if (i>nums.size())return c;
            else if (i<nums.size())
            {
             return  c+=recurse(nums,i+1,sum-nums[i],S,c)+recurse(nums,i+1,sum+nums[i],S,c);
    
            }
            return c;
             
        }
    
    
    
    public:
        int findTargetSumWays(vector<int>& nums, int S) 
        {   int i=0;long long int sum=0;int c=0;
            return recurse(nums,i,sum,S,c);    
        }
    };
    
    passes
    
    `
    public class Solution 
    {
        int count = 0;
        public int findTargetSumWays(int[] nums, int S) {
            calculate(nums, 0, 0, S);
            return count;
        }
        public void calculate(int[] nums, int i, int sum, int S) {
            if (i == nums.length) {
                if (sum == S)
                    count++;
            } else {
                calculate(nums, i + 1, sum + nums[i], S);
                calculate(nums, i + 1, sum - nums[i], S);
            }
        }
    }
    
    
    I am relatively new here sorry if this is trivial :)

Log in to reply
 

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