zoukankan      html  css  js  c++  java
  • Leetcode dfs Combination Sum

    Combination Sum

     Total Accepted: 17319 Total Submissions: 65259My Submissions

    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 be positive integers.
    • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • The solution set must not contain duplicate combinations.

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


    题意:给定一组数C和一个数值T,在C中找到全部总和等于T的组合。

    C中的同一数字能够拿多次。找到的组合不能反复。


    思路:dfs
    每一层的第i个节点有  n - i 个选择分支
    递归深度:递归到总和大于等于T就能够返回了
    复杂度:时间O(n!)。空间O(n)

    感觉測试数据有问题,我用以下两个代码。对于[1,1],1这个输入。输出的结果各自是[[1],[1]]和[[1]],但两个代码都 Accepted 了。我感觉第二个代码才是正确的,输出结果没反复。

    //代码一
    vector<vector<int> > res;
    vector<int> _nums;
    void dfs(int target, int start, vector<int> &path){
    	if(target == 0) res.push_back(path);
    	for(int i = start; i < _nums.size(); ++i){
    		if(target < _nums[i]) return ; //这里假设没剪枝的话会超时
    		path.push_back(_nums[i]);
    		dfs(target - _nums[i], i, path);
    		path.pop_back();
    	}
    }
    
    
    vector<vector<int> >combinationSum(vector<int> &nums, int target){
    	_nums = nums;
    	sort(_nums.begin(), _nums.end());
    	vector<int> path;
    	dfs(target, 0, path);
    	return res;
    }


    //代码二
    vector<vector<int> > res;
    vector<int> _nums;
    void dfs(int target, int start, vector<int> &path){
    	if(target == 0) res.push_back(path);
    	int previous = -1;
    	for(int i = start; i < _nums.size(); ++i){
    		if(_nums[i] == previous) continue;
    		if(target < _nums[i]) return ; //这里假设没剪枝的话会超时
    		previous = _nums[i];
    		path.push_back(_nums[i]);
    		dfs(target - _nums[i], i, path);
    		path.pop_back();
    	}
    }
    
    vector<vector<int> >combinationSum(vector<int> &nums, int target){
    	_nums = nums;
    	sort(_nums.begin(), _nums.end());
    	vector<int> path;
    	dfs(target, 0, path);
    	return res;
    }
    


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    安装虚拟环境virtualenv
    安装python3、ipython、jupyter
    配置yum源
    面向对象
    sqrt开平方算法的尝试,是的看了卡马克大叔的代码,我来试试用C#写个0x5f3759df和0x5f375a86跟System.Math.Sqrt到底哪个更强
    python开发环境
    phthon中的open函数模式
    picoscope 动态链接库调用位置确定,可进行图标编辑
    设计模式笔记(2)-工厂模式
    设计模式笔记(1)-单体模式
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4741834.html
Copyright © 2011-2022 走看看