zoukankan      html  css  js  c++  java
  • 40-Combination Sum II

    【问题】

    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 (a1, a2, … , 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] 

    【分析】

    1.与题一思路类似,只是在递归处参数改动

    【算法实现】

    //v1
    public class Solution {
        List<List<Integer>> res;
        List<Integer> temp;
        public List<List<Integer>> combinationSum2(int[] num, int target) {
            res=new ArrayList<List<Integer>>();
            temp=new ArrayList<Integer>();
            Arrays.sort(num);
            getCombination(num,target,0,0);       
            HashSet h = new HashSet(res);     //去除重复的list
            res.clear();
            res.addAll(h);
            return res;
        }
        
        public void getCombination(int[] num,int target,int sum,int level) {
            if(sum==target) {
                res.add(new ArrayList<Integer>(temp));
                return;
            }
            if(sum>target||level==num.length)
                return;
            for(int i=level;i<num.length;i++) {
                sum+=num[i];
                temp.add(num[i]);
                getCombination(num,target,sum,i+1);
                temp.remove(temp.size()-1);
                sum-=num[i];
            }
        }
    }
    //v2
    public
    class Solution { List<List<Integer>> result; List<Integer> solu; public List<List<Integer>> combinationSum2(int[] num, int target) { result = new ArrayList<>(); solu = new ArrayList<>(); Arrays.sort(num); getComboSum(num, target, 0, 0); return result; } public void getComboSum(int []num, int target, int sum, int level){ if(sum==target){ result.add(new ArrayList<>(solu)); return; } if(sum>target) return; for(int i=level;i<num.length;i++){ sum+=num[i]; solu.add(num[i]); getComboSum(num, target, sum, i+1); sum-=num[i]; solu.remove(solu.size()-1); while(i<num.length-1 && num[i]==num[i+1]) i++; //比较合适的做法 } } }
  • 相关阅读:
    影视-纪录片:《梵净山》
    NuGet:ServiceStack
    资源-产品:ServiceStack
    Win7x64安装Oracle11201x64 解决PLSQL Developer无法找到oci问题
    Oracle11g环境设置-windows环境
    安装sql server提示挂起报错
    安装oracle11g未找到文件WFMLRSVCApp.ear文件
    配置linux中文
    卸载rpm包提示:error: specifies multiple packages
    FileZilla简单介绍及运用
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4444846.html
Copyright © 2011-2022 走看看