2012-02-23 34 views
3

我正在研究一个项目,因为我们正在开始研究递归。我对此很新,所以我不知道如何解决这个难题。这是本书中的问题,我会很感激任何STEPS(step1,step2,...),这可能会帮助我想出办法来解决这个问题。另外,如果有人能够与我分享一种方法,我真的很感激理解递归,但它对我来说并没有什么意义,所以我会很感激关于如何更好地理解这个话题的任何建议。好的,这些是说明。谢谢。java中的递归Additionpuzzle

加法拼图的形式如2BCD + BCDE = DA01。我们想找到所有的解决方案,其中A,B,C,D是不同的数字,不同于谜题中的任何数字。这里,一个解决方案是2345 + 3456 = 5801。一般来说,一个谜题可以有多达十个数字和数字的任意组合。写一个递归方法使用这两类计算解决一个难题:

级#1

public class ThisPuzzle 
{ 
/** 
    Returns a solution to a puzzle. 
    @param p a puzzle 
    @return a solution or null if none exists 
*/ 
public static Puzzle solvePuzzle(Puzzle p) 
{ 
    // ... 
    return null; 
} 

public static void main(String[] args) 
{ 
    Puzzle p = new Puzzle("3A6", "36B", "71C"); 
    System.out.println(solvePuzzle(p)); 
} 
} 

类#2

public class Puzzle 
{ 
    private String add1; 
    private String add2; 
    private String result; 

    /** 
     Constructs a puzzle. 
     @param add1 a string containing digits 0 - 9 and letters 
     @param add2 a string containing digits 0 - 9 and letters 
     @param result a string containing digits 0 - 9 and letters 
    */ 
    public Puzzle(String add1, String add2, String result) 
    { 
     this.add1 = add1; 
     this.add2 = add2; 
     this.result = result; 
    } 

    /** 
     Makes a new puzzle by replacing a letter with a digit. 
     @param letter the letter to be replaced 
     @param digit the digit to replace it with 
     @return the new puzzle 
    */ 
    public Puzzle replace(String letter, int digit) 
    { 
     // ... 
    } 

    /** 
     Returns true if the puzzle is solved. 
     @return true if the puzzle has no letters and the 
     first two numbers add up to the third 
    */ 
    public boolean isSolved() 
    { 
     // ... 
    } 

    /** 
     Gets the first letter in this puzzle. 
     @return the first letter, or "" if there are no letters. 
    */ 
    public String firstLetter() 
    { 
     // ... 
    } 

    /** 
     Checks whether this puzzle contains a given digit. 
     @param digit a digit 
     @return true if this puzzle returns digit 
    */ 
    public boolean contains(int digit) 
    { 
     // ... 
    } 

    public String toString() 
    { 
     return add1 + "+" + add2 + "=" + result; 
    }  
} 

回答

2

递归是当你调用里面它自己的方法定义。

一个很简单的无限循环是:

public static void recurse(){ 
    recurse(); 
} 

调用此方法会导致堆栈溢出异常。如果您在递归过程中打印邮件,可能会更容易想象为什么会出现错误。你打打印之前,因为机器必须保持所有方法的调用堆栈中徒然希望内部递归将结束,它可以打印你的消息

public static void recurse(){ 
    recurse(); 
    System.out.println("finished recursing") 
} 

错误将被抛出。

对于您的问题,您需要在solvePuzzle中调用solvePuzzle。这个想法是你应该尝试在每个递归级别内解决更简单的谜题。想想试验和错误。