美文网首页
组合总和

组合总和

作者: 小白学编程 | 来源:发表于2018-11-04 18:27 被阅读0次

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

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

public class Solution {
    public List<List<Integer>> combinationSum(int[] nums, int target) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, target, 0);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
    if(remain < 0) return;
    else if(remain == 0) list.add(new ArrayList<>(tempList));
    else{ 
        for(int i = start; i < nums.length; i++){
            tempList.add(nums[i]);
            backtrack(list, tempList, nums, remain - nums[i], i); 
            tempList.remove(tempList.size() - 1);
        }
    }
}
}

组合总和

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> L = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        combination(candidates, L, list, target, 0);
        return L;
    }
    
    static void combination(int[] candidates, List<List<Integer>> L, List<Integer> list, int target, int index) {
        if (target == 0) {
            //L.add(list);
            L.add(new ArrayList(list));
            return ;
        }else if (target < 0){
            return ;
        }else {
            for (int i = index; i < candidates.length; i++) {
                if(i > index && candidates[i] == candidates[i-1]) continue;
                list.add(candidates[i]);
                combination(candidates, L, list, target - candidates[i], i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
}

相关文章

  • 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 组合总和

  • 组合总和

    Algorithm 39. Combination Sum[https://leetcode.com/proble...

  • LeetCode:组合总和

    组合总和 题目叙述: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 cand...

  • 2018-08-13 LeetCode回溯算法(组合总和)总结

    组合总和candidates 中的数字可以无限制重复被选取 组合总和 IIcandidates 中的每个数字在每个...

  • 39. 组合总和

    39. 组合总和 很慢的dfs

  • 39. 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • leetcode 39 组合总和

    今天很奇怪,我用的是dfs,AC代码是 但是前面一直用下面的代码,过不了 后来发现我这样写会改变sum的值,下次要...

  • 39.组合总和

    题目给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所...

  • 39.组合总和

网友评论

      本文标题:组合总和

      本文链接:https://www.haomeiwen.com/subject/rhkdxqtx.html