这类题太多了,换零钱,寻找多少个数和为定值,大同小异。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0) {
return res;
}
List<Integer> l = new ArrayList<Integer>();
Arrays.sort(candidates);
solve(candidates, 0, target, res, l);
return res;
}
public void solve(int[] a, int j, int target, List<List<Integer>> res, List<Integer> l) {
if (target == 0) {
List<Integer> temp = new ArrayList<Integer>(l);
res.add(temp);
return;
}
for (int i = j; i < a.length; i++) {
if (a[i] > target) {
return;
}
l.add(a[i]);
solve(a, i, target - a[i], res, l);
l.remove(l.size() - 1);
}
}
}
顺便统计解的个数:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0) {
return res;
}
List<Integer> l = new ArrayList<Integer>();
Arrays.sort(candidates);
System.out.println(solve(candidates, 0, target, res, l));
return res;
}
public static int solve(int[] a, int j, int target, List<List<Integer>> res, List<Integer> l) {
int c = 0;
if (target < 0) {
return 0;
}
if (target == 0) {
List<Integer> temp = new ArrayList<Integer>(l);
res.add(temp);
return 1;
}
int prev = -1;
for (int i = j; i < a.length; i++) {
if (prev != a[i]) {
l.add(a[i]);
c += solve(a, i + 1, target - a[i], res, l);
l.remove(l.size() - 1);
prev = a[i];
}
}
return c;
}
public static void main(String[] args) {
int[] a = {10, 1, 2, 7, 6, 1, 5};
combinationSum2(a, 8);
}
}
第二种写法:
public class Problem_01_CoinsWay {
public static int coins1(int[] arr, int aim) {
if (arr == null || arr.length == 0 || aim < 0) {
return 0;
}
return process1(arr, 0, aim);
}
public static int process1(int[] arr, int index, int aim) {
int res = 0;
if (index == arr.length) {
res = aim == 0 ? 1 : 0;
} else {
for (int i = 0; arr[index] * i <= aim; i++) {
res += process1(arr, index + 1, aim - arr[index] * i);
}
}
return res;
}
}