zoukankan      html  css  js  c++  java
  • LeetCode:39. Combination Sum(Medium)

    1. 原题链接

    https://leetcode.com/problems/combination-sum/description/

    2. 题目要求

    给定一个整型数组candidates[ ]和目标值target,找出数组中累加之后等于target的所有元素组合

    注意:(1)数组中的每一个元素可以重复用;(2)数组中不存在重复元素;(3)数组中都是正整数

    3. 解题思路

    采用迭代的方法检验所有元素组合

    4. 代码实现

     1 import java.util.ArrayList;
     2 import java.util.List;
     3 
     4 public class CombinationSum39 {
     5     public static void main(String[] args) {
     6         CombinationSum39 cs = new CombinationSum39();
     7         int[] candidates = {2,3,6,7};
     8         for (List l1:cs.combinationSum(candidates,7)){
     9             System.out.println(l1.toString());
    10             System.out.println();
    11         }
    12 
    13     }
    14     public List<List<Integer>> combinationSum(int[] candidates, int target) {
    15         List<List<Integer>> result = new ArrayList<List<Integer>>();
    16         combinationSum(result,new ArrayList<Integer>(),candidates,target,0);
    17         return result;
    18     }
    19     public void combinationSum(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) {
    20         if (target > 0) {
    21             for (int i = start;i < candidates.length;i++) { 
    22                 cur.add(candidates[i]);
    23                 combinationSum(result, cur, candidates, target-candidates[i],i);
    24                 cur.remove(cur.size() - 1);
    25             }
    26         }
    27         if (target == 0)
    28             result.add(new ArrayList<Integer>(cur));
    29     }
    30 }
  • 相关阅读:
    AGC002
    ICPC 北美Mid Central 2019 Regional
    【洛谷 5020】货币系统
    【洛谷 1109】学生分组
    【洛谷 2915】奶牛混合起来
    【洛谷 4162】最长距离
    【YCOJ 3805】竞选
    【洛谷 2807】最长路
    【洛谷 2918】买干草Buying Hay
    【LOJ 10172】涂抹果酱
  • 原文地址:https://www.cnblogs.com/huiAlex/p/8227434.html
Copyright © 2011-2022 走看看