C++ Combination Solution with explanation (not accepted)


  • 0
    S

    My solution was not accepted for the following test case : 20 - [2,16,14,15] which obviously should return 0. Basically, I am doing the combination of all the elements in the array and selecting the minimum size that satisfies the target. The expected output for the above input is '2' ins't that an error in the test case?

        bool matchTarget(vector<int> nums, int target){
            int val=0;
            for(int i:nums){
                val+=i;
            }
            return val==target;
        }
        
        void combination(vector<int> nums, vector<int> buff, int pos, int target, int &curr_min){
            if(matchTarget(buff, target)){
                curr_min = min(curr_min, static_cast<int>(buff.size()));
            }
            
            for(int i=pos; i<nums.size(); i++){
                buff.push_back(nums.at(i));
                combination(nums, buff, i+1, target, curr_min);
                buff.erase(buff.end()-1);
            }
        }
    
        int minSubArrayLen(int s, vector<int>& nums) {
            
            if(nums.size() == 0)
                return 0;
                
            int curr_min = INT_MAX;
             combination(nums, vector<int>(), 0, s, curr_min);
          
            if(curr_min == INT_MAX)
                return 0;
                
            return curr_min;
        }
    

Log in to reply
 

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