Leecode39 combination-sum

题目描述

给出一组候选数C和一个目标数T,找出候选数中加起来和等于T的所有组合。
C中的数字在组合中可以被无限次使用
注意:
题目中所有的数字(包括目标数T)都是正整数
你给出的组合中的数字 (a 1, a 2, … , a k) 要按非递增排序 (ie, a 1 ≤ a 2 ≤ … ≤ a k).
结解集中不能包含重复的组合
例如:给定的候选数集是[2,3,6,7],目标数是7
解集是:
[7]
[2, 2, 3]

分析

  • 使用回溯法

java 代码

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0 || target <= 0){return res;}
        
        Arrays.sort(candidates);
        combinationSumHelper(candidates,0,target,new ArrayList<Integer>(),res);
        
        return res;
    }
    public void  combinationSumHelper(int [] candidates,int index,int target,ArrayList<Integer> cur,ArrayList<ArrayList<Integer>> res){
         if(target == 0){
             res.add(new ArrayList<Integer> (cur));
         }else if(target > 0){
             for(int i = index; i < candidates.length; i++){
                 if(candidates[i] > target) break;
                 cur.add(candidates[i]);
                 combinationSumHelper(candidates,i,target - candidates[i],cur,res);
                 cur.remove(cur.size()-1);
             }
         }
     }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,062评论 0 2
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,428评论 0 2
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 声明:作者翻译论文仅为学习,如有侵权请...
    SnailTyan阅读 2,592评论 0 5
  • 基于学生学习共同体培育语文生态课堂文化的研究 近年来,随着现代教育理念的不断深入与...
    火车头123阅读 2,073评论 0 8
  • 9点睡,现在又醒了。总觉得不对劲,这几天一直做梦,我起来找原因! 去那个房间看了看女儿,果不其然她又在自己做饭吃,...
    313贺然阅读 184评论 0 1