首页 > Python资料 博客日记

组合求和2

2024-08-14 01:00:10Python资料围观41

Python资料网推荐组合求和2这篇文章给大家,欢迎收藏Python资料网享受知识的乐趣

题目描述:

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

求解思路:

使用回溯(backtrack)算法。首先将原数组candidates按照取值从小到大排序,然后依次寻找可能求和等于目标值target的子数组。

构建一维动态数组combination存放可能成为候选的子数组,构建二维动态数组存放所有符合要求的子数组res。

回溯算法在子程序中完成,目标是依次遍历已排序的数组candidates中每个值,并判断当前值是否可以作为构成候选子数组的一份子。

(1)如果“目标值-当前求和=0”,也就是候选子数组的求和已经等于目标值,则结束当前回溯子过程,并把满足条件的候选子数组combination存入res中。

(2)依次遍历candidates数组时,当前值如果没有和前一个值重复,并且“目标值>= 当前求和+当前值”,则当前值有可能作为候选项。

从当前位置的下一个位置重新进入回溯子程序,直至找到满足条件的候选子数组,或者“目标值< 当前求和+当前值”,因为数组candidates已经从小到大排序,所以后续值也不可能满足条件了。

每个当前值在结束回溯子程序后,当前值都要从候选项子数组中弹出,也就是每个较小的值(当前求和+当前值<=目标值)都有可能在候选列表中,也有可能不在候选列表中,要兼顾两种情况。

代码:

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> res;
        vector<int> combination;
        backtrack(res, combination, candidates, target, 0);
        return res;
    }
    void backtrack(vector<vector<int>> &res, vector<int> &combination, vector<int> &candidates, int target, int index){
        if (target ==0){
            res.push_back(combination);
            return;
        }
        for (int i = index; i<candidates.size()&& target>=candidates[i]; i++){
            if (i==index || candidates[i] != candidates[i-1]) {
                // not the same combination again
                combination.push_back(candidates[i]);
                backtrack(res, combination, candidates, target-candidates[i], i+1);
                combination.pop_back();
            }
        }
    }


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐