简体   繁体   English

查找您可以使用最多 m 个部分拆分 n 个对象的方法的数量

[英]function to find number of ways u can split n objects using parts up to m

I'm using recursion to solve the problem.我正在使用递归来解决问题。 On paper my answer should work so I went wrong with the code.在纸上,我的答案应该有效,所以我的代码出错了。 However, I can't figure exactly where the problem is.但是,我无法确切地确定问题出在哪里。

public class Partition {
    public static void main(String[] args) {
        System.out.println(part(6,4));
    }

    public static int part(int n, int m) {
        if (n==0) {
            return 1;
        }
        else if(m == 0 || n<0) {
            return 0;
        }
        else {
            return part(n-m, m) + part(n, m);
        }
    }
}

You need to reduce m only for the problem to return 9 as you indicated.您只需要减少m以使问题返回 9,如您所指示的。

public static int part (int n, int m) {
    if (n == 0) {
        return 1;
    } else if (m == 0 || n < 0) {
        return 0;
    } else {
        return part(n - m, m--) + part(n, m);
    }
}

I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :我不确定您要做什么,但是如果要计算组合,它应该如下所示:

public static int part(int n, int m) {
    if(m>n) { //This prevent a wrong input from the user
        return part(m, n);
    } else if (m==0 || m==n) { //This is your base case
        return 1;
    } else if(m < 0 || n<0) { //this should not happened, but you never know
        return 0;
    }  else { //this is where you're making mistake(s)
        //I don't know if I'm using the formula you are looking for
        //But if not, make sure yours do not use part(n, m) otherwise it will run forever
        return part(n-1, m) + part(n-1, m-1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将给定数量M随机分成N个部分 - Randomly split a given number M into N parts 找到你可以上n阶梯的所有方法,如果你可以一次采取k步,使k &lt;= n - Find all the ways you can go up an n step staircase if you can take k steps at a time such that k <= n Java 字符串拆分/删除 n 个特殊字符部分 - Java String Split/Remove for n number of special charactor parts 我如何编写一个 function ,它将数字(n)作为输入并自动为 class 创建(n)个对象 - How can i write a function which takes number(n) as input and automatically creates (n) number of objects for a class 找出将 n 表示为两个有边界整数之和的方法的数量 - Find the number of ways to represent n as a sum of two integers with boundaries 将数字分为两部分 - Split number into two parts Java:将日期拆分为 n 个部分 - Java : Split Date by n parts 找出N和M之间的每个数字可以表示为一对素数之和的次数 - Find how many times each number between N and M can be expressed as a sum of a pair of primes 一个http mutlipart请求可以将文件分成多个部分吗? - Can one http mutlipart request split up the file in multiple parts? 找出两个皇后在n * n棋盘上相交(不稳定)的方式? - Find out the Number of ways in which two queens intersects (won't be stable) on n*n chessboard?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM