leetcode 39-Combination Sum

来源:互联网 发布:html引导页源码 编辑:程序博客网 时间:2024/06/07 05:22

和40题非常相似
自己写的代码 非常耗时间 (版本一)

public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> list = new ArrayList<>();        List<Integer> temp = new ArrayList<>();        backtrack(list, temp, candidates, target, 0, 0);        return deduplicate(list);    }    private void backtrack(List<List<Integer>> list, List<Integer> temp, int[] candidates, int target, int index, int sum) {        if (sum > target) return;        if (sum == target) list.add(new ArrayList<Integer>(temp));        if (sum < target) {            for (int i = 0; i < candidates.length; i++) {                temp.add(candidates[i]);                backtrack(list, temp, candidates, target, i + 1, sum + candidates[i]);                temp.remove(temp.size() - 1);            }        }    }    private List<List<Integer>> deduplicate(List<List<Integer>> list) {        list.forEach(l -> Collections.sort(l));        return list.stream().distinct().collect(Collectors.toList());    }

又写了一个,但是还有可以优化的地方

public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> list = new ArrayList<>();        List<Integer> temp = new ArrayList<>();        backtrack(list, temp, candidates, target, 0, 0);        return list;    }    private void backtrack(List<List<Integer>> list, List<Integer> temp, int[] candidates, int target, int index, int sum) {        if (sum > target) return;        if (sum == target) list.add(new ArrayList<Integer>(temp));        if (sum < target) {            for (int i = index; i < candidates.length; i++) {                temp.add(candidates[i]);                backtrack(list, temp, candidates, target, i, sum + candidates[i]);                temp.remove(temp.size() - 1);            }        }    }

比如说,【2 3 6 7】 target = 7;
判断完 2222之后,2223,2226,2227就不需要在判断了。但是这个程序还进行了判断,就是说剪枝做的不好。前提是【2 3 6 7】按照升序排好了。

0 0
原创粉丝点击