获取,加起来一个给定数的所有可能的和 [英] Getting all possible sums that add up to a given number

查看:162
本文介绍了获取,加起来一个给定数的所有可能的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如:

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

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

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

解决方案

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

从:<一href="http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html">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&GT; = 1;我 - ){
            分区(N-I,I,preFIX ++ I);
        }
    }


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

}
 

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);
    }

}

这篇关于获取,加起来一个给定数的所有可能的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆