杭电2566_统计硬币——java

Problem Description
假设一堆由1分、2分、5分组成的n个硬币总面值为m分,求一共有多少种可能的组合方式(某种面值的硬币可以数量可以为0)。
 

Input
输入数据第一行有一个正整数T,表示有T组测试数据;
接下来的T行,每行有两个数n,m,n和m的含义同上。
 

Output
对于每组测试数据,请输出可能的组合方式数;
每组输出占一行。
 

Sample Input
 
 
2
3 5
4 8
 

Sample Output
 
 
1
2

看到该题的思路是母函数求解,想了一下DFS也可以,以下的DFS方法AC的代码,

之后有空再补个母函数的代码。

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while ((T--) != 0) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            System.out.println(dfs(5,n,m));
        }
    }

    public static int dfs(int current, int n, int m) {

        int count = 0;
        if(n ==0 && m == 0)
            return 1;
        if(n==0 || m<1)
            return 0;
        if (current == 5) {
            count = count + dfs(5, n - 1, m - 5);
            count = count + dfs(2, n - 1, m - 2);
            count = count + dfs(1, n - 1, m - 1);
        } else if (current == 2) {
            count = count + dfs(2, n - 1, m - 2);
            count = count + dfs(1, n - 1, m - 1);
        } else if (current == 1 ) {
            count = count + dfs(1, n - 1, m - 1);
        }
        return count;
    }
}

DP做法

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        while (T-- != 0) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            int[][] dp = new int[n + 1][m + 1];
            int[] data = {1, 2, 5};
            dp[0][0] = 1;
            for (int i = 0; i < 3; i++) {
                for (int j = 1; j <= n; j++) {
                    for (int k = data[i]; k <= m; k++) {
                            dp[j][k] += dp[j - 1][k-data[i]];
                    }
                }
            }
            System.out.println(dp[n][m]);
        }
    }
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值