LeetCode 第39题:Combination Sum (Java详解)

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

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

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

题目解析:
找寻目标值相加的排序组合,允许值重新;
1.先给给定数字进行排序;
2.每次从给定数字第一位开始遍历,先将第一个值加入临时数组中,而后进行递归调用,目标值更新为
target-candidates[0];依次进行遍历,最后target等于0,这一组数字组成的排列即符合要求。

代码:

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        //返回列表
        List> resultList = new LinkedList<>();
        //暂存列表
        List tempList = new LinkedList<>();
        //先排序
        Arrays.sort(candidates);
        CombinaList(candidates,target,0,tempList,resultList);
        return resultList;
    }
    //2,3,5  target = 8
    public void CombinaList(int[] candidates, int target,int index,List tempList,List> resultList)
    {
        if(target < 0)
        {
            return;
        }
        else if(target == 0)//正确选项
        {
            resultList.add(new LinkedList<>(tempList));
        }
        else
        {
            for(int i = index;i

性能:
LeetCode 第39题:Combination Sum (Java详解)_第1张图片

总结:正在转Java中,性能一般,各位大佬有好的VIP课程,可分享给我,谢谢!

你可能感兴趣的:(Java)