2020.08.02-LeetCode 39

99 阅读1分钟

给定一个数组、给定一个目标值。求所有组合为该目标值的组合。

public static void main(String[] args) {
        int[] nums = {1, 2, 2, 2, 5};
        combinationSum2(nums, 8);

    }
    public static List<List<Integer>> combinationSum2(int[] cand, int target) {
           
         //排序
        Arrays.sort(cand);

        List<List<Integer>> result = new LinkedList<>();

        List<Integer> path = new ArrayList<>();

		//深度优先搜搜。
        dfs_com(cand, 0, target, path, result);

        return result;
    }

    static void dfs_com(int[] cand, int cur, int target, List<Integer> path, List<List<Integer>> res) {
        //目标值为0
        if (target == 0) {
            res.add(new ArrayList(path));
            return;
        }
		
        //小于该目标值则剪枝。
        if (target < 0) {
            return;
        }

        for (int i = cur; i < cand.length; i++) {
            if (i > cur && cand[i] == cand[i - 1]) {
                continue;
            }
            path.add(path.size(), cand[i]);
            //递归
            dfs_com(cand, cur + 1, target - cand[i], path, res);
            //回溯
            path.remove(path.size() - 1);
        }
    }