LeetCode 039 Combination Sum

题目描述

Given a set of candidate numbers (C) 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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,

A solution set is:

[7] 
[2, 2, 3] 

代码

    ArrayList> result;
    ArrayList cur;
    int[] candidates;
    int target;

    public List> combinationSum(int[] candidates, int target) {

        if (candidates == null || candidates.length == 0) {
            return new ArrayList>();
        }

        result = new ArrayList>();
        cur = new ArrayList();

        this.candidates = candidates;
        this.target = target;

        Arrays.sort(candidates);
        dfs(0, target);

        return result;
    }

    void dfs(int j, int target) {

        // 找到解,存到result中
        if (target == 0) {
            result.add(new ArrayList(cur));
            return;
        }

        for (int i = j; i < candidates.length; i++) {

            // 如果小于就返回,表明此后不会有解了!
            if (candidates[i] > target) {
                return;
            }

            // 递归求解
            cur.add(candidates[i]);
            dfs(i, target - candidates[i]);
            cur.remove(cur.size() - 1);
        }
    }

你可能感兴趣的:(leetcode,LeetCode)