Combination Sum II

来源:互联网 发布:千牛淘宝店铺怎么改名 编辑:程序博客网 时间:2024/06/15 18:40
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {        // Start typing your Java solution below        // DO NOT write main() function        if(num.length == 0) return null;        Arrays.sort(num);        return combinationSum2(num, 0, target);    }        public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int start, int target) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();        if(target <= 0) {            if(target == 0) result.add(new ArrayList<Integer>());            return result;        }        for(int i = start; i < num.length; i++) {            for(ArrayList<Integer> sub : combinationSum2(num, i + 1, target - num[i])) {                //pay attention here                sub.add(0,num[i]);                set.add(sub);            }        }        result.addAll(set);        return result;    }    //don't use hashset, but it must sorted first    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {        // Start typing your Java solution below        // DO NOT write main() function        if(num.length == 0) return null;        Arrays.sort(num);        return combinationSum2(num, 0, target);    }        public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int start, int target) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        if(target <= 0) {            if(target == 0) result.add(new ArrayList<Integer>());            return result;        }        for(int i = start; i < num.length; i++) {            for(ArrayList<Integer> sub : combinationSum2(num, i + 1, target - num[i])) {                //pay attention here                sub.add(0,num[i]);                result.add(sub);            }            while(i < num.length - 1 && num[i] == num[i + 1]) i++;        }        return result;    }


原创粉丝点击