zoukankan      html  css  js  c++  java
  • 花店摆花问题

    参考代码

     1 public class baihua {
     2     private static int n,m,sum;
     3     private static int[] s;
     4     public static void main(String[] args) {
     5         String str = new Scanner(System.in).nextLine();
     6         n = Integer.parseInt(str.split(" ")[0]);
     7         m = Integer.parseInt(str.split(" ")[1]);
     8         s = new int[n];
     9         str = new Scanner(System.in).nextLine();
    10         for(int i=0;i<n;i++){
    11             s[i] = Integer.parseInt(str.split(" ")[i]);
    12         }
    13         dg(0,0);
    14         System.out.println(sum%1000007);
    15     }
    16     private static void dg(int index,int num) {
    17         if(num == m){
    18             sum++;
    19         }
    20         if(index >= n || num >= m){
    21             return;
    22         }else{
    23             for(int i=0;i<=s[index];i++){
    24                 dg(index+1,num+i);
    25             }
    26         }
    27     }
    28 }

    运行结果

    算法解析

    dg方法使用了回溯算法,不断尝试。
    其中第一个参数为当前花种,因为存储每种花摆放上限的数组s是从0开始的,所有0为第一种花
    第二个参数所有花摆放数量总和

    注意代码dg方法中代码“for(int i=0;i<=s[index];i++)”,因为有些花可以不摆,只要达到规定的摆放数量即可,所有循环开始时i=0,如果加上必须每种花都要摆的条件的话则可以改为i=1

  • 相关阅读:
    new delate he typedef的含义
    Importing the multiarray numpy extension module failed
    QT socket相关
    CMake的一些使用
    CMake undefined reference to `QTcpServer::QTcpServer(QObject*)'的解决
    MFC操作excel
    dsview
    phyton 相关学习
    面试相关
    远程连接
  • 原文地址:https://www.cnblogs.com/chengpu/p/algorithm4.html
Copyright © 2011-2022 走看看