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


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代表路径满足条件,添加路径到结果集
            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); //当从当前节点的所有路径都搜索完毕后,将其剔除,之后重新搜索从下一个节点开始的所有路径
        }
    }
}

 

猜你喜欢

转载自www.cnblogs.com/tengdai/p/9257134.html