参考代码:
package com.cfl;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static List<List<Integer>> findSumCombinations(int n, int m) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), n, m, 0, 0);
return result;
}
private static void backtrack(List<List<Integer>> result, List<Integer> currentList, int n, int m, int start, int sum) {
if (currentList.size() == n && sum == m) {
result.add(new ArrayList<>(currentList));
return;
}
if (currentList.size() < n) {
for (int i = start; i <= m - (n - currentList.size()) * start; i++) {
currentList.add(i);
backtrack(result, currentList, n, m, i, sum + i);
currentList.remove(currentList.size() - 1); // 回溯,移除当前尝试的数
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
String[] split = str.split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
List<List<Integer>> combinations = findSumCombinations(n, m);
combinations.removeIf(combination -> combination.get(0) == 0);
List<List<Integer>> temp = new ArrayList<>();
for (List<Integer> combination : combinations) {
for (int i = 0; i < combination.size(); i++) {
if(i==combination.size()-1){
break;
}
if(combination.get(i+1)-combination.get(i)>3){
//System.out.println(combination);
temp.add(combination);
}
}
}
//System.out.println("---------------------------------");
for (int i = 0; i < combinations.size(); i++) {
for (int j = 0; j < temp.size(); j++) {
if(combinations.get(i) == temp.get(j)){
combinations.remove(i);
}
}
}
// for (List<Integer> combination : combinations) {
// System.out.println(combination);
// }
System.out.println(combinations.size());
}
}