6/01/2014

83. Combination Sum II

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
        ArrayList<Integer> temp = new ArrayList<Integer> ();
        getlist(candidates, target, res, temp, 0);
        return res;
    }
 
    public void getlist(int[] candidates, int target, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> temp, int start) {
        if (target==0) {
            ArrayList<Integer> temp2 = new ArrayList<Integer> (temp); //不太明白思密达
            if (!res.contains(temp2)) res.add(temp2);
            return;
        }
     
        for (int i=start; i<candidates.length; i++) {
            if (target-candidates[i]>=0) {
                temp.add(candidates[i]);
                getlist(candidates, target-candidates[i], res, temp, i+1);
                temp.remove(temp.size()-1);
            }
        }
    }
}

没有评论:

发表评论