【问题标题】:Number of score combinations, dynamic programming help, ( from elements of programming interviews, java)分数组合的数量,动态编程帮助,(来自编程面试的元素,java)
【发布时间】: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


    【解决方案1】:

    我不知道你的代码有什么问题,但看起来很难理解。

    有一种更简单、更容易解决的方法,无需递归。

    步骤:

    • 创建一个数组dp,大小为target + 1
    • points 中的每个点更新dp
    import java.util.List;
    import java.util.Arrays;
    
    public class Main
    {   
        static int noOfWays(List<Integer> points, int target) {
            
            int[] dp = new int[target + 1];
            dp[0] = 1;
            for(int point: points)
                for(int i = point; i <= target; i++)
                    dp[i] += dp[i - point];
    
            return dp[target];
        }
    
        public static void main(String[] args) {
            List<Integer> points = Arrays.asList(1, 3);
            int target = 6;
            System.out.println(noOfWays(points, target));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 2023-03-26
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多