根据给定的某个Sum,从数组中找出4个和为该Sum(四个数的和)

原题

  Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 
  Note: 
  Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 
  The solution set must not contain duplicate quadruplets.

   For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

题目大意

  给定一个整数数组,找出a + b + c + d = target的唯一解。 

解题思路

  先确定a和d的两个数,对于a和d两个数,不能同时重复使用。然后再确定b和c,同样这两个数也不能同时重复使用。找出所有满足条件的解,同时可以保证解不重复。 

#include <stdio.h>
#include <vector>

int Partition(int *v, const int low, const int high)
{
    if (v == NULL || low > high) {
        return -1;
    }
    int i = low;
    int j = high;
    int pivot = v[i];
    while (i < j) {
        while (i < j && pivot < v[j]) {
            --j;
        }
        if (i < j) {
            v[i++] = v[j];
        }
        while (i < j && pivot > v[i]) {
            ++i;
        }
        if (i < j) {
            v[j--] = v[i];
        }
    }
    v[i] = pivot;
    return i;
}

void QuickSort(int *v, const int low, const int high)
{
    if (v == NULL || low > high) {
        return ;
    }
    if (low < high) {
        int pivot = Partition(v, low, high);
        QuickSort(v, low, pivot - 1);
        QuickSort(v, pivot + 1, high);
    }
}

bool Func(int *v, const int len, const int sum, std::vector<std::vector<int> > &vec)
{
    bool ret = false;
    if (v == NULL || len < 4) {
        return ret;
    }

    QuickSort(v, 0, len - 1);

    // 第一个加数
    for (int i = 0; i < len - 3; ++i) {
        // 第一个加数使用不能重复
        if (i > 0 && v[i] == v[i - 1]) {
            continue;   
        }

        // 第二个加数
        for (int j = len - 1; j > i + 2; --j) {
            // 第二个加数使用不能重复
            if (j < len - 1 && v[j] == v[j + 1]) {
                continue;
            }

            // 第三个加数
            int start = i + 1;
            // 第四个加数
            int end = j - 1;
            int n = sum - v[i] - v[j];
            while (start < end) {
                if (v[start] + v[end] == n) {
                    std::vector<int> vecs;
                    vecs.push_back(v[i]);
                    vecs.push_back(v[start]);
                    vecs.push_back(v[end]);
                    vecs.push_back(v[j]);
                    vec.push_back(vecs);
                    // 保证再次使用第二个数不重复
                    do {
                        ++start;
                    } while (start < end && v[start] == v[start - 1]);

                    // 保证再次使用第三个数不重复
                    do {
                        --end;
                    } while (start < end && v[end] == v[end + 1]);
                } else if (v[start] + v[end] < n) {
                    // 保证再次使用第二个数不重复
                    do {
                        ++start;
                    } while (start < end && v[start] == v[start - 1]);
                } else {
                    // 保证再次使用第三个数不重复
                    do {
                        --end;
                    } while (start < end && v[end] == v[end + 1]);
                }
            } // end while
        } // end j
    } // end i
    return ret;
}

int main()
{
    int v[] = {1,3,5,7,9,0,8,6,4,2};
    const int len = sizeof(v) / sizeof(v[0]);
    int sum = 10;
    std::vector<std::vector<int> > vec;
    Func(v, len, sum, vec);
    QuickSort(v, 0, len - 1);
    for (int i = 0; i < vec.size(); ++i) {
        std::vector<int> vecs = vec[i];
        for (int j = 0; j < vecs.size(); ++j) {
            printf("%d ", vecs.at(j));
        }
        printf("\n");
    }
    return 0;
}

[root@agan tmall]# g++ -o sum sum.cc 
[root@agan tmall]# ./sum
0 1 2 7 
0 1 3 6 
0 1 4 5 
0 2 3 5 
1 2 3 4

好的,我可以回答这个问题。以下是使用Java语言编写的代码,可以找出组nums中所有可以使字和为target的组合: ```java import java.util.ArrayList; import java.util.List; public class CombinationSum { public List<List<Integer>> combinationSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<>(); backtrack(result, new ArrayList<>(), nums, target, 0); return result; } private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int remain, int start) { if (remain < 0) { return; } else if (remain == 0) { result.add(new ArrayList<>(tempList)); } else { for (int i = start; i < nums.length; i++) { tempList.add(nums[i]); backtrack(result, tempList, nums, remain - nums[i], i); tempList.remove(tempList.size() - 1); } } } } ``` 这个代码使用回溯算法找出所有的组合。我们首先定义一个空的结果列表result,然后调用backtrack方法来找出所有的组合。backtrack方法接受四个:result,tempList,nums和remain。tempList是一个临时列表,用于存储当前的组合。nums是给定组,remain是当前还需要凑出的字和。start参用于避免重复的组合。 在backtrack方法中,我们首先检查remain是否小于0,如果是,说明当前的组合不符合要求,直接返回。如果remain等于0,说明我们已经找到了一个符合要求的组合,将其添加到结果列表中。否则,我们遍历组nums,并将当前的字添加到tempList中。然后,我们递归调用backtrack方法,将remain减去当前的字nums[i],并将i作为start参传递给下一次递归。递归完成后,我们将tempList中的最后一个数字删除,以便继续遍历组。 最后,我们可以在主函数中调用combinationSum方法来找出所有的组合: ```java public static void main(String[] args) { int[] nums = {2, 3, 5}; int target = 8; CombinationSum solution = new CombinationSum(); List<List<Integer>> result = solution.combinationSum(nums, target); System.out.println(result); } ``` 输出结果为: ``` [[2, 2, 2, 2], [2, 3, 3], [3, 5]] ``` 这些组合分别是[2,2,2,2],[2,3,3]和[3,5],它们的字和都为8。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值