美文网首页
39. 组合总和

39. 组合总和

作者: 梦想黑客 | 来源:发表于2020-03-03 17:02 被阅读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]
]

解法

class Solution {

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

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

        List<Integer> item = new ArrayList<>();
        generate(0,candidates,target,item);

        return result;
    }

    private void generate(int start,int[] candidates,int target,List<Integer> item){
        if(target < 0){
            return;
        }

        if(target == 0){
            result.add(new ArrayList<>(item));
        }else{
            for(int i=start; i<candidates.length; i++){
                item.add(candidates[i]);
                generate(i,candidates,target - candidates[i],item);
                item.remove(item.size() - 1);
                continue;
            }

        }
    }
}

相关文章

  • 39. 组合总和

    39. 组合总和 很慢的dfs

  • 39. 组合总和

    39. 组合总和 https://leetcode-cn.com/problems/combination-sum...

  • 39. 组合总和

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

  • 39.组合总和

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

  • 39.组合总和

  • 39.组合总和

    Given a set of candidate numbers (candidates) (without du...

  • 39.组合总和

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

  • 39. 组合总和

    解题思路 典型的回溯法:递归跳出的条件return 满足题目条件将list加入容器else 未满足条件:for(遍...

  • 39. 组合总和

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

  • 39. 组合总和

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

网友评论

      本文标题:39. 组合总和

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