码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Combination Sum

时间:2018-02-04 21:05:42      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:ble   tor   换问题   logs   .com   chosen   经典的   contain   set   

Combination Sum 题解

题目来源:https://leetcode.com/problems/combination-sum/description/


Description

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 (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

Solution

class Solution {
private:
    void backTrack(vector<int>& path, vector<vector<int> >& res,
                   vector<int>& candidates, int begin, int target) {
        if (target == 0) {
            res.push_back(path);
        } else {
            int size = candidates.size();
            if (begin >= size)
                return;
            for (int i = begin; i < size; i++) {
                if (candidates[i] <= target) {
                    path.push_back(candidates[i]);
                    backTrack(path, res, candidates, i, target - candidates[i]);
                    path.pop_back();
                }
            }
        }
    }
public:
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        vector<vector<int> > res;
        vector<int> path;
        backTrack(path, res, candidates, 0, target);
        return res;
    }
};

解题描述

这道题类似与经典的零钱兑换问题,在给定的数组candidates,找出所有和为target的数字组合,选择的数字可以重复但解法不能重复。上面使用的是递归回溯的办法,类似DFS,不难理解,下面再多给出使用迭代DP的解法:

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        vector<vector<vector<int> > > dp(target + 1, vector<vector<int> >());
        dp[0].push_back(vector<int>());
        for (auto candidate : candidates) {
            for (int j = candidate; j <= target; j++) {
                if (!dp[j - candidate].empty()) {
                    auto paths = dp[j - candidate];
                    for (auto& path : paths)
                        path.push_back(candidate);
                    dp[j].insert(dp[j].end(), paths.begin(), paths.end());
                }
            }
        }
        return dp[target];
    }
};

[Leetcode] Combination Sum

标签:ble   tor   换问题   logs   .com   chosen   经典的   contain   set   

原文地址:https://www.cnblogs.com/yanhewu/p/8414113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!