循环和递归(后记)

循环和递归(后记)昨天那个题目简单了一点 今天增加一点难度

要求在 输入一个整数n,然后使用递归算法在一个JTextArea中输出所有 1到n的路径。
例如n=4,则输出: 
            1-4
            1-2-4 
            1-3-4
            1-2-3-4

多了一句红色的1-3-4,多了这一句就麻烦多了

试了不少方法,感觉用正则最容易

代码如下:


循环代码:

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumTest { public static void main(String[] args) { int x = 1, y, z; String str = ""; Scanner scan = new Scanner(System.in); y = scan.nextInt(); while(x < y){ str += x +"-"; System.out.println(str + y); z = x + 1; while(z < y){ if(x == 1){ z = y; }else{//用正则把相应的x替换成z String str1 ="" + x, str2 = "" + z; Pattern p = Pattern.compile(str1); Matcher m = p.matcher(str); System.out.println(m.replaceAll(str2)+y); z++; } } x++; } } }

递归代码:

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NumTest1 { static String str = ""; public static void main(String[] args) { int x = 1, y, z = x + 1; Scanner scan = new Scanner(System.in); y = scan.nextInt(); /* while(x < y){ str += x +"-"; System.out.println(str + y); z = x + 1; while(z < y){ if(x == 1){ z = y; }else{//用正则把相应的x替换成z String str1 ="" + x, str2 = "" + z; Pattern p = Pattern.compile(str1); Matcher m = p.matcher(str); System.out.println(m.replaceAll(str2)+y); z++; } } x++; }*/ digui(x, y, z); } public static int digui(int x, int y, int z){ if(x == y){ return x; }else{ str += x +"-"; System.out.println(str + y); z = x + 1; while(z < y){ if(x == 1){ z = y; }else{//用正则把相应的x替换成z String str1 ="" + x, str2 = "" + z; Pattern p = Pattern.compile(str1); Matcher m = p.matcher(str); System.out.println(m.replaceAll(str2)+y); z++; } } return digui(x + 1, y, z); } } }

感觉代码有一些要优化的地方,有时间再做了

你可能感兴趣的:(算法,优化,String,Class,import)