zoukankan      html  css  js  c++  java
  • (Java) LeetCode 39. Combination Sum —— 组合总和

    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]
    ]
    

    经典深度优先搜索+回溯问题。因为candidates数组是没有重复的,且每个数字都可以用无限次,代表每次搜索的时候都要从自己开始。而当所有从自己出发的路径考虑完毕后,要把自己剔除出去(即回溯)进而搜索下一个数值。如果用有向图的思想,把每个数组下标都想成一个节点,节点之间的权值是从这个节点下标出发时对应的数组元素(即出权值),那么问题转化为寻找权值为target的路径。每一个节点都可以连通到其他节点,且每个节点又都有自环。模型想象到这里就更容易理解下面的代码。


    Java

    class Solution {
        public static List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if(candidates == null) return res;
            List<Integer> list = new ArrayList<>(); //存放路径上的节点
            get(candidates, 0, target, list, res);
            return res;
        }
        
        public static void get(int[] nums, int i, int target, List<Integer> list, List<List<Integer>> res) {
            if (target < 0) return; //如果路径值小于0,搜索结束,因为所有权值都是大于零,即一旦达到负数没有办法再回到0
            if (target == 0) { //如果目标为0代表路径权值和已经满为target,满足条件,故添加路径到结果集
                res.add(new ArrayList<>(list)); //
                return;
            }
            for (int p = i; p < nums.length; p++) { 
                list.add(nums[p]); //添加节点到路径
                get(nums, p, target - nums[p], list, res); //在已有路径基础上继续查找更新权值后后的路径,因为有自环,所以还是从自身节点开始搜索
                list.remove(list.size() - 1); //当从当前节点的所有路径都搜索完毕后,将其剔除,之后重新搜索从下一个节点开始的所有路径
            }
        }
    }

     

  • 相关阅读:
    关于document.onkeydown
    kubernetes PV存储卷类型 Marathon
    0015leetcode算法实现之三数之和3sumpython&golang实现 Marathon
    0018leetcode算法实现之四数之和4sumpython&golang实现 Marathon
    ubuntu20.04调整时区时间同步 Marathon
    0054leetcode算法实现之螺旋矩阵spiralMatrixpython&golang实现 Marathon
    0005剑指offer替换空格python&golang实现 Marathon
    使用 kubectl 管理 Secret Marathon
    0058leetcode算法实现之左翻转字符串reverseLeftStringpython%golang实现 Marathon
    0059leetcode算法实现之螺旋矩阵IIspiralMatrixIIpython&golang实现 Marathon
  • 原文地址:https://www.cnblogs.com/tengdai/p/9257134.html
Copyright © 2011-2022 走看看