小明有n个可选运动,每个运动有对应卡路里,想选出其中k个运动且卡路里和为t。
k,t,n都是给定的。求出可行解数量。
输入描述:
第一行输入 n t k,用空格进行分割
第二行输入 每个运动的卡路里 按照空格进行分割
输出描述:求出可行解数量
import java.util.*;
public class Main{
static List<List<Integer>> res = new ArrayList<>();
static List<Integer> temp = new ArrayList<>();
static int tCheck = 0;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
int k = sc.nextInt();
int[] ns = new int[n];
for(int i = 0; i < n; i++){
ns[i] = sc.nextInt();
}
backTracking(ns, t, k, 0);
System.out.print(res.size());
}
public static void backTracking(int[] ns, int t, int k, int start){
if(temp.size() == k){
if(tCheck == t){
res.add(new ArrayList<>(temp));
}
return;
}
// 剪枝
if(tCheck > t){
return;
}
for(int i = start; i < ns.length; i++){
temp.add(ns[i]);
tCheck += ns[i];
backTracking(ns, t, k, i + 1);
temp.remove(temp.size() - 1);
tCheck -= ns[i];
}
}
}








网友评论