【发布时间】:2020-10-19 02:41:52
【问题描述】:
给定单个比赛的得分和最终目标得分,目标是计算可能组合的数量。 (例如,如果目标分数为 6 并且播放分数为 ,则有 3 种方法可以达到目标分数 - 3x2、3x1 + 1x3、1x6)
我不明白为什么我的代码是错误的:
import java.util.*;
public class Main
{
public static int combinations(int target, List<Integer> plays) {
Collections.sort(plays);
HashMap<Integer, Integer> map = new HashMap<>(); //map score to combinations.
map.put(0,1);
combHelper(target,plays,plays.size() -1, map);
return map.get(target);
}
private static int combHelper(int target, List<Integer> plays, int i, HashMap<Integer, Integer> map) {
if (target < 0 || i < 0) {
return 0;
}
if (!map.containsKey(target)) {
int out = combHelper(target,plays,i - 1, map) + combHelper(target - plays.get(i),plays,i,map);
map.put(target,out);
}
return map.get(target);
}
public static void main(String[] args) {
List<Integer> points = new ArrayList<>(Arrays.asList(3,1));
System.out.println(combinations(6,points)); //output is 2
}
}
任何帮助和反馈将不胜感激!
【问题讨论】:
标签: java recursion dynamic-programming