刷题39. Combination Sum

一、题目说明

题目39. Combination Sum,是从正数列表中选取几个,其和等于目标数的可能组合。任何一个数可以重复取,如candidates = [2,3,6,7], target = 7,结果集合是[ [7], [2,2,3] ]

如candidates = [2,3,5], target = 8,结果集合是 [ [2,2,2,2], [2,3,3], [3,5] ]

题目难度是Medium,先思考一下,再来解答。

二、我的解答

经过一番思考,这个题目可以通过dfs(树的深度优先遍历)求解,首先我们画一个“树”,反映求解过程。这个图,我就不上了。我的代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution{
    public:
        void dfs(vector<vector<int>>& res,vector<int>& candidates,vector<int>& path,int begin,int target){
            if(target==0){
                res.push_back(path);
                return;
            }
            for(int i=begin;i<candidates.size() && target-candidates[i]>=0;i++){
                path.push_back(candidates[i]);
                dfs(res,candidates,path,i,target-candidates[i]);
                path.pop_back();
            }
        }
        vector<vector<int>> combinationSum(vector<int>& candidates, int target){
            vector<vector<int>> res;
            vector<int> path;
            if(candidates.size()<1){
                return res;
            }
            sort(candidates.begin(),candidates.end());
            dfs(res,candidates,path,0,target);
            return res;
        }
};
int main(){
    Solution s;
    vector<int> candidates = {2,3,6,7};
    vector<vector<int>> res = s.combinationSum(candidates,7);
    cout<<"candidates of {2,3,6,7}"<<"\n";
    for(int i=0;i<res.size();i++){
        vector<int> r = res[i];
        for(int j=0;j<r.size();j++){
            cout<<r[j]<<" ";
        }
        cout<<"\n";
    }

    cout<<"candidates of {2,3,5}"<<"\n";
    candidates = {2,3,5};
    res = s.combinationSum(candidates,8);
    for(int i=0;i<res.size();i++){
        vector<int>r = res[i];
        for(int j=0;j<r.size();j++){
            cout<<r[j]<<" ";
        }
        cout<<"\n";
    }
    return 0;
}

性能:

Runtime: 12 ms, faster than 84.44% of C++ online submissions for Combination Sum.
Memory Usage: 9.8 MB, less than 58.33% of C++ online submissions for Combination Sum.

一行代码没修改,再次运行:

Runtime: 4 ms, faster than 99.94% of C++ online submissions for Combination Sum.
Memory Usage: 9.3 MB, less than 94.44% of C++ online submissions for Combination Sum.

三、优化

比较搞笑的是,我一行代码没修改,再次提交性能居然大幅提高。厉害了!

另外的解答思路是DP,这个是网上的,不是我写的。

用unordered_map<int, vector<vector>> dict;存储数的分解,比如求{2,3,5,7}和是8的:

dict[2] ={2}

dict[3] = {3}

dict[4] = {2,2}

dict[5] = dict[2] + dict[3] = {2,3}

dict[6] = {dict[2] + dict[2] + dict[2]},{dict[3]}

....

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int> &candidates, int target)
    {
        unordered_map<int, vector<vector<int>>> dict;
        for (int i = 1; i <= target; i++)
            for (int it : candidates)
                if (i == it){
                    dict[i].push_back(vector<int>{ it });
                }
                else if (i > it){
                    for (auto ivec : dict[i - it]) {
                        if (it < ivec[ivec.size() - 1]) {
                            continue;
                        }
                        ivec.push_back(it);

                        dict[i].push_back(ivec);
                    }
                }

        return dict[target];
    }
};

原文地址:https://www.cnblogs.com/siweihz/p/12240964.html

时间: 2024-11-08 19:36:38

刷题39. Combination Sum的相关文章

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

[array] leetcode - 39. Combination Sum - Medium

leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from

39. Combination Sum I/II

基础backtracing题,先排序一下,每次传一个参数表示开始的下标. class Solution { public: vector<vector<int>> res; vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(),candidates.end()); vector<int>

[Leetcode][Python]39: Combination Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 39: Combination Sumhttps://oj.leetcode.com/problems/combination-sum/ Given a set of candidate numbers (C) and a target number (T),find all unique combinations in C where the candidate numbers

leetCode 39.Combination Sum(组合总和) 解题思路和方法

Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (includi

93. Restore IP Addresses--back tracking -- 类比39 Combination Sum

93 给你 一串数字,让你求出可能的IP 地址. Input: "25525511135" Output: ["255.255.11.135", "255.255.111.35"] 仔细分析一下这题和39题 几乎完全一样呀,39是给你 一个没有重复数组,可以重复使用数组里的数字之和来组成 target. Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,

39. Combination Sum java solutions

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will

LeetCode 39. Combination Sum (组合的和)

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (in

Java [Leetcode 39]Combination Sum

题目描述: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target)