算法:回溯三 Combination Sum组合总数

说明

题目地址:https://leetcode.com/problems/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]
]

解法

思路:对candidate数组进行排序,对candidate中的每个元素可以选择加,也可以选择不加;可以选择重复,也可以选择不重复。这里不仅要用到回溯,也要用到for循环。两个判断条件:

  1. target == 0 则把列表添加到结果列表中,注意这个列表用clone,如果用索引list,结果会被修改掉。resultList.add(new ArrayList<>(list))
  2. target > 0 则判断是否要加入当前元素。
package backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// https://leetcode.com/problems/combination-sum/
public class CombinationSum {

  public static void main(String[] args) {
    CombinationSum obj = new CombinationSum();
    int[] candicates = {2, 3, 6, 7};
    int target = 7;
    List<List<Integer>> resultList = obj.combinationSum(candicates, target);
    System.out.println(Arrays.toString(resultList.toArray()));
  }

  public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> resultList = new ArrayList<>();
    Arrays.sort(candidates);
    recursive(candidates, target, 0, new ArrayList<>(), resultList);

    return resultList;
  }

  public void recursive(int[] candidates, int target, int start, List<Integer> list, List<List<Integer>> resultList) {
    if (target > 0) {
      for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
        list.add(candidates[i]);
        recursive(candidates, target - candidates[i], i, list, resultList);
        list.remove(list.size() - 1);
      }
    } else if (target == 0) {
      resultList.add(new ArrayList<>(list));
    }
  }
}

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/CombinationSum.java

发布了127 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/zgpeace/article/details/103760393