获取,加起来一个给定数的所有可能的和定数、加起来

2023-09-11 22:37:28 作者:那一抹嫣红

我正在为Android的数学应用程序。在这些领域中,用户可以输入一个int之一(没有数字和以上0)。这样做是为了得到所有可能的和,使这个中断,没有双打(4 + 1 == 1 + 4在这种情况下)。已知的唯一的一点是这一个int类型。

例如:

说用户输入4,我想应用程序返回:

4 3 + 1 2 + 2 2 + 1 + 1 1 + 1 + 1 + 1

显然4 == 4,使得应添加太多。任何建议,我应该如何去这样做?

解决方案

下面是一个简单的算法,声称这样做

从:http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html

 公共类分区{

    公共静态无效的分区(INT N){
        分区(N,N,);
    }
    公共静态无效的分区(INT N,INT最大,串preFIX){
        如果(N == 0){
            StdOut.println(preFIX);
            返回;
        }

        的for(int i = Math.min(最大,N); I> = 1;我 - ){
            分区(N-I,I,preFIX ++ I);
        }
    }


    公共静态无效的主要(字串[] args){
        INT N =的Integer.parseInt(参数[0]);
        分区(N);
    }

}
 
20个数字EXCEL其中5个数字不规则加起来等于一个固定数

I'm making an math app for the android. In one of these fields the user can enter an int (no digits and above 0). The idea is to get all possible sums that make this int, without doubles (4+1 == 1+4 in this case). The only thing known is this one int.

For example:

Say the user enters 4, I would like the app to return:

4 3+1 2+2 2+1+1 1+1+1+1

Obviously 4 == 4 so that should be added too. Any suggestions as to how i should go about doing this?

解决方案

Here's a simple algorithm that purports to do that

from : http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html

public class Partition { 

    public static void partition(int n) {
        partition(n, n, "");
    }
    public static void partition(int n, int max, String prefix) {
        if (n == 0) {
            StdOut.println(prefix);
            return;
        }

        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(n-i, i, prefix + " " + i);
        }
    }


    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        partition(N);
    }

}