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

    Combination Sum II

     Total Accepted: 13710 Total Submissions: 55908My Submissions

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    Each number in C may only be used once in the combination.

    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 10,1,2,7,6,1,5 and target 8
    A solution set is: 
    [1, 7] 
    [1, 2, 5] 
    [2, 6] 
    [1, 1, 6] 




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

    C中的同一数字最多仅仅能拿一次。找到的组合不能反复。
    思路:dfs
    第i层的第j个节点有  n - i - j 个选择分支
    递归深度:递归到总和大于等于T就能够返回了
    复杂度:时间O(n!),空间O(n)

    vector<vector<int> > res;
    vector<int> _num;
    void dfs(int start, int target, vector<int> &path){
    	if(target == 0) {res.push_back(path); return;}
    	int previous = -1; //这里要加上这个来记录同一层分枝的前一个值。假设当前值跟前一个值一样。就跳过,避免反复
    	for(int i = start; i < _num.size(); ++i){
    		if(previous == _num[i]) continue;
    		if(target < _num[i]) return; //剪枝
    		previous = _num[i];
    		path.push_back(_num[i]);
    		dfs(i + 1, target - _num[i], path);
    		path.pop_back();
    	}
    }
    vector<vector<int> > combinationSum2(vector<int> &num, int target){
    	_num = num;
    	sort(_num.begin(), _num.end());
    	vector<int> path;
    	dfs(0, target, path);
    	return res;
    }


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

  • 相关阅读:
    webpack之理解loader
    React中需要多个倒计时的问题
    react.js中实现tab吸顶效果问题
    利用浏览器调试APP中的H5页面
    css一长串连续英文字符的换行
    纯css实现移动端横向滑动列表
    javascript数据结构——写一个二叉搜索树
    javascript数据结构——链表
    javascript数组去重
    《正则表达式必知必会(修订版)》笔记
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4618566.html
Copyright © 2011-2022 走看看