数组中相加之和等于特定值的元素

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> result = new ArrayList<>();
        if (candidates == null)
            return result;
        Arrays.parallelSort(candidates);
        return combinationSum(candidates, target, 0);
    }

    public List> combinationSum(int[] candidates, int target, int start) {
        List> result = new ArrayList<>();
        for (int i = start; i < candidates.length; i++) {
            if (i > start && candidates[i] == candidates[i - 1])
                continue;
            if (candidates[i] < target) {
                for (List list : combinationSum(candidates, target - candidates[i], i)) {
                    list.add(0, candidates[i]);
                    result.add(list);
                }
            } else if (candidates[i] == target) {
                List res = new ArrayList<>();
                res.add(candidates[i]);
                result.add(res);
            } else {
                break;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {2, 2, 3, 7};
        int target = 7;
        System.out.println(new Solution().combinationSum(nums, target));
    }
}

[参考]
https://discuss.leetcode.com/topic/24818/easy-to-understand-96-performance-java-solution
https://discuss.leetcode.com/topic/46161/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning

你可能感兴趣的:(编程学习)