【LeetCode】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 (a1a2, … , 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] 

个人在第一个题目还没有思路的时候先做的,开始想用DP,但是没有成功,最后用深度遍历算法。找出所有的路径。以为会超时,但是还是AC了

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        if(num.length==0)
            return re;
        ArrayList<Integer> al = new ArrayList<Integer>();
        Arrays.sort(num);
        FindPath(num,al,target,0,num.length-1);
        re.addAll(remap.keySet());
        return re;
        
    }
    public  Map<ArrayList<Integer>,Integer> remap = new HashMap<ArrayList<Integer>,Integer>();
    public ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
   private void FindPath(int[] num, ArrayList<Integer> al, int target, int start, int end) {
        
        if(start>end)
            return;
        for(int i=start;i<=end;i++){
            al.add(num[i]);
            int temp = sum(al);
            if(temp==target){
                ArrayList<Integer> at = new ArrayList<Integer>();
                for(int j=0;j<al.size();j++){
                    at.add(al.get(j));
                }
                remap.put(at, 1);
                al.remove(al.size()-1);
                return;
            }
            if(temp<target){
                FindPath(num,al,target,i+1,end);
                al.remove(al.size()-1);
                
            }else{
                al.remove(al.size()-1);
                return;
            }
            
        }
    }
   private int sum(ArrayList<Integer> al) {
        int re=0;
        for(int i=0;i<al.size();i++){
            re+=al.get(i);
        }
        return re;
    }
}
原文地址:https://www.cnblogs.com/yixianyixian/p/3746506.html