zoukankan      html  css  js  c++  java
  • [array] leetcode

    leetcode - 40. Combination Sum II - Medium

    descrition

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

    解析

    leetcode - 39. Combination Sum - Medium 类似,只是这里的数组元素存在重复,并且元素不可重复取。

    代码只实现了其中一种递归形式,这样的实现方法递归层数应该是最浅的。

    code

    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    class Solution{
    public:
    	vector<vector<int> > combinationSum2(vector<int> &candidates, int target){
    		vector<vector<int> > ans;
    		vector<int> vecCur;
    		sort(candidates.begin(), candidates.end());
    		combinationSum2Backtracking(candidates, 0, vecCur, target, ans);
    		return ans;
    	}
    
    	void combinationSum2Backtracking(vector<int>& candidates, int index,
    						             vector<int>& vecCur, int target,
    						             vector<vector<int> > &ans){
    		if(target < 0)
    			return;
    		if(target == 0){
    			if(!vecCur.empty())
    				ans.push_back(vecCur);
    			return;
    		}
    
    		for(int i=index; i<candidates.size(); i++){
    			if(candidates[i] > target) // candidates mush in ascending order
    				break;
    			// choose candidates[i], and each number in candidates may only
    			// be used onece in combination
    			vecCur.push_back(candidates[i]);
    			combinationSum2Backtracking(candidates, i+1, vecCur, target - candidates[i], ans);
    			// don't choose candidates[i]
    			vecCur.pop_back();
    
    			// skip the duplicate
    			while((i+1)<candidates.size() && candidates[i+1] == candidates[i])
    				i++;
    			// after i++, i will point to a new unique number
    		}
    	}
    };
    
    int main()
    {
    	return 0;
    }
    
    
    
  • 相关阅读:
    what's the python之异常处理
    what's the python之面向对象(进阶)
    what's the python之面向对象
    what's the python之自定义模块和包
    Java并发编程-并发工具包(java.util.concurrent)使用指南(全)
    Java之JUC系列:外部Tools
    java CS结构软件自动升级的实现
    史上最全最强SpringMVC详细示例实战教程
    搭建最简单的SpringMVC框架(使用maven)
    小心对待query_cache_size
  • 原文地址:https://www.cnblogs.com/fanling999/p/7846176.html
Copyright © 2011-2022 走看看