Ksum 问题

Ksum,用backtracking来做,转换成1sum or 2sum,

3Sum: https://leetcode.com/problems/3sum/description/

4Sum: https://leetcode.com/problems/4sum/description/

class Solution {
public:
    
    void find1Sum(vector> &allcomb, vector &comb, vector& nums, int target, int start){
        for(int i=start; i> &allcomb, vector &comb, vector& nums, int target, int start){
        int left = start, right = nums.size()-1;
        while(left < right){
            int sum = nums[left] + nums[right];
            if(sum == target){
                comb.push_back(nums[left]);
                comb.push_back(nums[right]);
                allcomb.push_back(comb);
                comb.pop_back();
                comb.pop_back();
                left++; right--;
                while(nums[left] == nums[left-1]) left++;
                while(nums[right] == nums[right+1]) right--;
            }
            else if(sum < target){
                left++;
            }
            else{
                right--;
            }
        }
    }
    
    void find4Sum(vector> &allcomb, vector &comb, vector& nums, int target, int start, int k){
        if(k <= 0){
            return;
        }
        
        else if(k == 1){
            find1Sum(allcomb, comb, nums, start, target);
            return;
        }
        else if(k == 2){
            find2Sum(allcomb, comb, nums, target, start);
            return;
        }
        
        for(int i=start; i<=nums.size()-k; i++){
            if(i > start && nums[i] == nums[i-1]){
                continue;
            }
            
            comb.push_back(nums[i]);
            find4Sum(allcomb, comb, nums, target-nums[i], i+1, k-1);
            comb.pop_back();
        }
    }
    
    vector> fourSum(vector& nums, int target) {
        vector> allcomb;
        if(nums.size() < 4){
            return allcomb;
        }
        
        vector comb;
        sort(nums.begin(), nums.end());
        find4Sum(allcomb, comb, nums, target, 0, 4);
        return allcomb;
    }
};

你可能感兴趣的:(Ksum 问题)