【每日一题】39. Combination Sum

时间:2022-07-23
本文章向大家介绍【每日一题】39. Combination Sum,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目描述

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

题解

和2Sum、3Sum问题类似,但是问题更宽泛,并不要求元素的个数,只要数字组合之和等于target即可,而且数字可以被重复选取,比如例子1中,target为7,组合[2,2,3]中2被选择了两次。

言归正传,对于这个问题,首先想到的解法是dfs,深度优先遍历,或者说是递归方法。问题规模可以逐渐减小,target-> target-a -> target-a-b -> 0;当target为0,说明已经找到一个组合,然后向上“归”,不断选择数字。

为了减少重复次数,避免每次递归时都从下标0开始,我们先对数组进行排序,然后再进行递归,递归时为了保证数字能重复选择, 下次递归时起始坐标包含选择的当前数字。

具体代码:

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        vector<int> temp;
        sort(candidates.begin(),candidates.end());
        backtrack(result, temp, candidates, target, 0);
        
        return result;
    }
private:
    void backtrack(vector<vector<int>>& all, vector<int>& temp, vector<int>& nums, int remain, int start){
        if(remain < 0) return;
        else if(remain == 0) all.push_back(temp);
        else{
            for(int i=start; i<nums.size(); i++){
                temp.push_back(nums[i]);
                backtrack(all, temp, nums, remain-nums[i], i);
                temp.pop_back();
            }
        }
    }
};