zoukankan      html  css  js  c++  java
  • 40. Combination Sum II(midum, backtrack, 重要)

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

    这题用到 backtrack 方法, 需去重.
    e.g.
    A = [1 1 2 5 6 7 10], target = 8
    正确输出应该是:
    [[1,1,6],[1,2,5],[1,7],[2,6]]

    难点在去重条件: * 我写的,错误: `if(i >= 1 && A[i] == A[i - 1]) continue;` - 错误输出: `[[1,2,5],[1,7],[2,6]]` * 人家写的,正确: `if ((i >= 1) && (A[i] == A[i - 1]) && (i > start)) continue;`

    差别就是 i > start 条件,挺不容易的想出来的.

    自己想法,自个代码(被人家修正^^):

    // backtrack
    // A = [1 1 2 5 6 7 10]
    vector<vector<int>> combinationSum2(vector<int>& A, int ta) {
    	sort(A.begin(), A.end());
    	vector < vector<int> > res;
    	vector<int> temp;
    	backtrack(A, res, temp, ta, 0);
    	return res;
    }
    
    void backtrack(vector<int>& A, vector<vector<int> >& res, vector<int> temp,
    		int remain, int start) {
    	if (remain < 0)
    		return;
    	else if (remain == 0)
    		res.push_back(temp);
    	else {
    		for (int i = start; i < A.size(); i++) {
    
    			// not correct: if(A[i] == A[i - 1] && i >= 1) continue;
    			// (i > start) is hard think, but important.
    
    			if ((i >= 1) && (A[i] == A[i - 1]) && (i > start))
    				continue; // check duplicate combination
    
    			temp.push_back(A[i]);
    			backtrack(A, res, temp, remain - A[i], i + 1); // i + 1, next element
    			temp.pop_back();
    		}
    	}
    }
    
  • 相关阅读:
    Redis02——Redis单节点安装
    Redis01——Redis产生背景
    验证元素的唯一性(二重循环法和快排优化)
    线性同余法的伪随机数
    转载(为啥要对10000007取模)
    (算法专题)使用常微分方程将递归转换为非递归
    算法设计与分析——习题一
    PAT Basic 1030 完美数列 (25 分)
    禁止yum update 自动更新系统内核
    Redis AOF 持久化方式
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7504323.html
Copyright © 2011-2022 走看看