前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【每日一题】39. Combination Sum

【每日一题】39. Combination Sum

作者头像
公众号-不为谁写的歌
发布2020-08-24 10:56:41
2240
发布2020-08-24 10:56:41
举报
文章被收录于专栏:桃花源记桃花源记

题目描述

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:

代码语言:javascript
复制
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

代码语言:javascript
复制
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开始,我们先对数组进行排序,然后再进行递归,递归时为了保证数字能重复选择, 下次递归时起始坐标包含选择的当前数字。

具体代码:

代码语言:javascript
复制
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();
            }
        }
    }
};

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 题解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档