zoukankan      html  css  js  c++  java
  • Leetcode: 39. Combination Sum

    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]
    ]
    

    思路

    • dfs
    • 按照下图方式剪枝,可保证没有重复

    代码

    class Solution {
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    		vector<vector<int>> res;
    
    		sort(candidates.begin(), candidates.end());
    		
    		vector<int> tmp;
    		dfs(candidates, target, candidates.size(), 0, res, tmp, 0);
    		
    
    		return res;
    	}
    
    	bool dfs(vector<int> &candidates, int target, int len, int t, vector<vector<int>> &res, vector<int> &tmp, int sum){
    		if (sum == target){
    			res.push_back(tmp);
    			return true;
    		}
    
    		else if (sum < target){
    			for (int i = t; i < len; ++i){
    				if (sum + candidates[i] > target) return false;
    				sum += candidates[i];
    				tmp.push_back(candidates[i]);
    				bool flag = dfs(candidates, target, len, i, res, tmp, sum);
    				
    				sum -= candidates[i];
    				tmp.pop_back();
    				
    				if (flag){
    					break;
    				}
    			}
    		}
    
    		return false;
    	}
    };
    
  • 相关阅读:
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Kooboo CMS
    Ajax.BeginForm VS Html.BeginForm
    ASP.NET或者 js方式实现文件夹多图片浏览的方式
    C++入门知识总结(1)
    几个步骤轻松搞定ASP.NET 依赖注入。
    使用GIT@OSChina 实现协同工作的方法。
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6841706.html
Copyright © 2011-2022 走看看