题解 | #加起来和为目标值的组合(二)#
加起来和为目标值的组合(二)
https://www.nowcoder.com/practice/75e6cd5b85ab41c6a7c43359a74e869a
import java.util.*; public class Solution { private ArrayList<ArrayList<Integer>> res = new ArrayList<>(); public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { if (num == null || num.length < 1) { return res; } Arrays.sort(num); backtrack(num, 0, target, new ArrayList<>()); return res; } private void backtrack(int[] num, int start, int target, List<Integer> list) { if (list.size() > 0 && target == 0) { res.add(new ArrayList<>(list)); return; } for (int i = start; i < num.length; i++) { if (target - num[i] < 0) { break; } if (i > start && num[i] == num[i - 1]) { continue; } target -= num[i]; list.add(num[i]); backtrack(num, i + 1, target, list); target += num[i]; list.remove(list.size() - 1); } } }