Algorithm that takes an integer and returns all possible format of addition(采用整数并返回所有可能的加法格式的算法)
问题描述
我需要编写一个算法,它接受一个整数并返回所有可能的加法格式
I need to write an algorithm that takes an integer and returns all possible format of addition
例如
如果我进入: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
这是我的尝试:
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;
            }
            // ...
        }
    }
}
推荐答案
我同意 Brad.完成此操作的最佳方法可能是通过递归.事实上,我昨晚正在研究与此相关的事情.我使用递归回溯算法解决了我的问题.查看维基百科页面:回溯
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.
但有一点需要注意,即 0.您可以将任意数量的零放入加法/减法中,结果会相同.
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.
这篇关于采用整数并返回所有可能的加法格式的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:采用整数并返回所有可能的加法格式的算法
				
        
 
            
        - Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
 - 从 finally 块返回时 Java 的奇怪行为 2022-01-01
 - 将log4j 1.2配置转换为log4j 2配置 2022-01-01
 - C++ 和 Java 进程之间的共享内存 2022-01-01
 - Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
 - Eclipse 插件更新错误日志在哪里? 2022-01-01
 - 如何使用WebFilter实现授权头检查 2022-01-01
 - value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
 - Jersey REST 客户端:发布多部分数据 2022-01-01
 - Java包名称中单词分隔符的约定是什么? 2022-01-01
 
						
						
						
						
						