|
| 1 | +package com.blankj.custom.pretest; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +public class DiceSum { |
| 8 | + |
| 9 | + public static void main(String[] args) { |
| 10 | + int[] candidates = {1, 2, 3, 4, 5, 6}; |
| 11 | + int target = 610; |
| 12 | + System.out.println(combination(candidates, target).size()); |
| 13 | + } |
| 14 | + |
| 15 | + public static List<List<Integer>> combination(int[] candidates, int target) { |
| 16 | + List<List<Integer>> res = new LinkedList<List<Integer>>(); |
| 17 | + List<Integer> tmp = new LinkedList<Integer>(); |
| 18 | + // 先将数组排序避免重复搜素 |
| 19 | + Arrays.sort(candidates); |
| 20 | + helper(res, candidates, target, 0, tmp); |
| 21 | + return res; |
| 22 | + } |
| 23 | + |
| 24 | + private static void helper(List<List<Integer>> res, int[] candidates, int target, int index, List<Integer> tmp) { |
| 25 | + // 如果当前和已经大于目标,说明该路径错误 |
| 26 | + if (target < 0) { |
| 27 | + return; |
| 28 | + // 如果当前和等于目标,说明这是一条正确路径,记录该路径 |
| 29 | + } else if (target == 0) { |
| 30 | + List<Integer> oneComb = new LinkedList<Integer>(tmp); |
| 31 | + res.add(oneComb); |
| 32 | + // 否则,对剩余所有可能性进行深度优先搜索 |
| 33 | + } else { |
| 34 | + // 选取之后的每个数字都是一种可能性 |
| 35 | + for (int i = index; i < candidates.length; i++) { |
| 36 | + // 典型的先加入元素,再进行搜索,递归回来再移出元素的DFS解法 |
| 37 | + if (i > 0 && candidates[i] == candidates[i - 1]) |
| 38 | + continue; |
| 39 | + tmp.add(candidates[i]); |
| 40 | + helper(res, candidates, target - candidates[i], i, tmp); |
| 41 | + tmp.remove(tmp.size() - 1); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments