算法,取整数,并返回除了所有可能的格式整数、算法、格式

由网友(我方水晶)分享简介:我需要写一个算法,取整数,并返回除了所有可能的格式为:例如。如果我eneter:6 这将返回下面的字符串:0 + 6 = 61 + 1 + 1 + 1 + 1 + 1 = 61 + 1 + 1 + 1 + 2 = 61 + 1 + 1 + 3 = 61 + 1 + 4 = 61 + 5 = 62 + 1 + 1 + 1...

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

例如。

如果我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] =我;
            }
            // ...
        }
    }
}
 
一个编辑框里的两个数相加怎么写代码 比如1 2结果在编辑框2里显示

解决方案

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

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

有一点要注意虽然,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.

阅读全文

相关推荐

最新文章