39. 组合总和

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。

candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。

对于给定的输入,保证和为 target 的唯一组合数少于 150 个。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {

    private static void solve(int[] candidates, List<List<Integer>> ret, LinkedList<Integer> path, int index, int target) {
        if (index == candidates.length) {
            return;
        }
        if (target == 0) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if (target >= candidates[index]) {
            path.offerLast(candidates[index]);
            solve(candidates, ret, path, index, target - candidates[index]);
            path.pollLast();
        }
        solve(candidates, ret, path, index + 1, target);
    }


    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return new ArrayList<>(0);
        }

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

        solve(candidates, ret, new LinkedList<>(), 0, target);

        return ret;
    }
}
posted @ 2021-12-03 10:57  Tianyiya  阅读(39)  评论(0)    收藏  举报