算法,取整数,并返回除了所有可能的格式 [英] Algorithm that takes an integer and returns all possible format of addition

查看:144
本文介绍了算法,取整数,并返回除了所有可能的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个算法,取整数,并返回除了所有可能的格式为:

例如。

如果我eneter:6

这将返回下面的字符串:

  0 + 6 = 6
 1 + 1 + 1 + 1 + 1 + 1 = 6
 1 + 1 + 1 + 1 + 2 = 6
 1 + 1 + 1 + 3 = 6
 1 + 1 + 4 = 6
 1 + 5 = 6
 2 + 1 + 1 + 1 + 1 = 6
 2 + 1 + 1 + 2 = 6
 2 + 1 + 3 = 6
 2 + 4 = 6
 3 + 1 + 1 + 1 = 6
 3 + 1 + 2 = 6
 3 + 3 = 6
 4 + 1 + 1 = 6
 4 + 2 = 6
 5 + 1 = 6
 6 + 0 = 6
 

下面是我的尝试:

 进口的java.util。*;
公共类测试
{
    公共静态无效的主要(字串[] args)
    {
        扫描仪在=新的扫描仪(System.in);
        System.out.print(输入的整数);
        INT NUM = in.nextInt();
        的System.out.println();
        计算(NUM);
    }
    私有静态无效计算(INT N)
    {
        INT [] arInt =新INT [N];
        的for(int i = 0; I< = N;我++)
        {
            对于(INT J = 0; J< = N; J ++)
            {
                arInt [J] =我;
            }
            // ...
        }
    }
}
 

解决方案

我同意布拉德。完成这一点的最好办法很可能是通过递归。事实上,我在做一些与此相关的最后一晚。我使用的是递归回溯算法,解决了我的问题。退房的维基百科页面:回溯

现在,我不作任何保证,有没有更好的,更简单的方式来解决这个问题。然而,随着递归回溯,你会发现所有的解决方案。

有一点要注意虽然,0。您可以抛出零的任意量到加法/减法,它会出来一样。

I need to write an algorithm that takes an integer and returns all possible format of addition

e.g.

If I eneter: 6

it would return the following String:

 0+6=6
 1+1+1+1+1+1=6
 1+1+1+1+2=6
 1+1+1+3=6
 1+1+4=6
 1+5=6
 2+1+1+1+1=6
 2+1+1+2=6
 2+1+3=6
 2+4=6
 3+1+1+1=6
 3+1+2=6
 3+3=6
 4+1+1=6
 4+2=6
 5+1=6
 6+0=6

Here is my try:

import java.util.*;
public class Test
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer? ");
        int num = in.nextInt();
        System.out.println();
        calculate(num);
    }
    private static void calculate(int n)
    {
        int[] arInt = new int[n];
        for(int i = 0; i <= n; i++)
        {
            for(int j = 0; j <= n; j++)
            {
                arInt[j] = i;
            }
            // ...
        }
    }
}

解决方案

I agree with Brad. The best way to complete this would probably be through recursion. In fact, I was working on something related to this last night. I solved my problem using a recursive backtracking algorithm. Check out the Wikipedia page: Backtracking

Now, I make no guarantees that there aren't better, less complex ways to solve this. However, with recursive backtracking you will find all the solutions.

One thing to watch out for though, that 0. You can throw any amount of zeros into an addition/subtraction and it will come out the same.

这篇关于算法,取整数,并返回除了所有可能的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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