leetcode解题方案--039-- CombinationSum

来源:互联网 发布:linux 查看数据包 编辑:程序博客网 时间:2024/05/29 10:44

题目

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

分析

这道题是求所有和为target的情况。和数独差不多。挨个试。
每当添加一个新值时,如果仍未达到target,则将target-当前和作为下一个target。并创建一个新的分支。如:
刚开始列表只有一个元素
2
2 2
2 3
2 6!
2 7!
第二次
2 2 2
2 2 3*
2 2 6!
2 2 7!
2 3 3!
2 3 6!
2 3 7!

class Solution {    public static List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> ret  = new LinkedList<>();        // 2 3 6 7        //7;2 2 3        Arrays.sort(candidates); // sort the array        recurse(new ArrayList<Integer>(), target, candidates, 0, ret);        return ret;    }    private static void recurse(List<Integer> list, int target, int[] candidates, int index, List<List<Integer>> result) {         if (target == 0) {            result.add(list);            return;        }        for (int i = index; i<candidates.length; i++) {            int newTar = target-candidates[i];            if (newTar>=0) {                List<Integer> copy = new ArrayList<>(list);                copy.add(candidates[i]);                recurse(copy, newTar,candidates, i, result);            } else {                break;            }        }    }}
原创粉丝点击