818. Subset With Target

Code(Language:C++)
class Solution {
public:
    /**
     * @param nums: the array
     * @param target: the target
     * @return: the number of subsets which meet the following conditions
     */
    long long subsetWithTarget(vector<int> &nums, int target) {
        // Write you code here
        // two pointers
        const int size = nums.size();
        if(size == 0){
            return 0;
        }
        sort(nums.begin(), nums.end()); 
        int left = 0; 
        int right = size - 1; 
        long long cnt = 0; 
        while(left <= right){
            if(nums[left] + nums[right] >= target){
                right--; 
            }
            else{
               cnt += pow(2, right - left); 
               left++;
            }
        }
        return cnt; 
    }
};

Comments

Popular posts from this blog

算法的比较