zoukankan      html  css  js  c++  java
  • 39. Combination Sum(medium, backtrack 的经典应用, 重要)

    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 the target) will be positive integers.
    • 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]
    ]
    

    本题是 backtrack(回溯法) 的经典应用.通过本题,仔细观察 backtrack 基本框架,并感受其应用.
    另外, subset 的题目也用 backtrack 方法.

    人家想法,自个代码:

    • cpp 副产品: v.pop_back(); 弹出队尾元素.
    • 要注意的是: 下面代码中 backtrack 方法中的 res, temp, A, 尤其是 temp, 他们都分别指向对应的一个对象,无论 backtrack 方法被嵌套地调用多少次!
    // backtrace method
    vector<vector<int>> combinationSum(vector<int>& A, int ta) {
    	sort(A.begin(), A.end());
    	vector < vector<int> > res;
    	vector<int> temp;
    	backtrack(res, temp, A, ta, 0);
    	return res;
    }
    
    void backtrack(vector<vector<int> >& res, vector<int>& temp, vector<int>& A,
    		int remain, int start) {
    	if (remain < 0)
    		return;
    	else if (remain == 0) {
    		res.push_back(temp);
    		return;
    	} else {
    		for (int i = start; i < A.size(); i++) {
    			temp.push_back(A[i]);
    
    			// not i + 1, because A[i] might be reused.
    			backtrack(res, temp, A, remain - A[i], i);
    
    			temp.pop_back();
    		}
    		return;
    	}
    }
    
  • 相关阅读:
    Android_Spinner_example
    23.pyspider安装
    22.Windows及linux下gerapy使用
    21.scrapy爬虫部署
    12.利用kakatips对网站数据信息监控
    11.启信宝数据二次筛选解密(字符串的分割与拼接及正则匹配)-2
    10.Ubuntu操作系统及python2.7、3.5 exe
    9.数据库多表一起查询
    8.代理ip使用
    7.阿布云代理服务器试用
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7503480.html
Copyright © 2011-2022 走看看