• 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++; //比较合适的做法 } } }
  • 相关阅读:
    用FOR XML PATH('') 实现一列多行拼接为一行
    RTC相关文章收集
    XML-RPC vs. RTC Format
    获取当前月份的第一天
    image读取流
    WAMP解决访问后显示"You don't have permission to access / on this server."
    cxGrid之checkbox小结
    CXGRID用法(取行、列值;定位选中某行等等)
    delphi显示Sqlite的Text字段
    使用TRoleAuth类对DataSnap服务端的接口授权
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4444846.html
Copyright © 2020-2023  润新知