java - 使用递归打印所有数字序列

标签 java algorithm recursion

所以我在我的计算机算法课上有这个作业: 编写一个递归算法,给定一个正整数 n >= 1,打印所有 数列 k >= 1 和 1 <= i1 < i2 <...< ik <= n。 例如:如果 n=3,那么输出将是

1

1,2

1,2,3

1,3

2

2,3

3

我试图用 Java 为这个赋值编写递归代码,但我不知道如何解决这个问题。我了解递归的基础知识,但我自己写递归代码有困难。

这是我现在拥有的:

public class question4
{  
    public static void main(String arg[]){
        int x = 10;
        printSequence(x);
    }
   public static int printSequence(int n){
       if (n == 1){
           System.out.println(n);
           return n;
       }
       else{
           int result = printSequence(n-1) + 1;
           System.out.println(result);
           return result;
       }
   }

} 

它只打印 1,2,3,4,5,6,7,8,9,10

请帮帮我!

提前致谢!

最佳答案

基本上,以n = 5为例,你应该打印两种间隔

 1          | full interval
 1 2        |
 1 2 3      |
 1 2 3 4    |
 1 2 3 4 5  |

 1 _ 3 4 5  | concatenation of full interval (1 -> i) with (i+1 -> n)
 1 2 _ 4 5  |
 1 2 3 _ 5  |

 1 _ _ 4 5  | concatenation of full interval (1 -> i) with (i+2 -> n)
 1 2 _ _ 5  | 

 1 _ _ _ 5  | concatenation of full interval (1 -> i) with (i+3 -> n)
 ---------------------
   2        | full interval
   2 3      |
   2 3 4    |
   2 3 4 5  |

   2 _ 4 5  | concatenation of full interval (1 -> i) with (i+1 -> n)
   2 3 _ 5  |

   2 _ _ 5  | concatenation of full interval (1 -> i) with (i+2 -> n)
 ---------------------
     3      | full interval
     3 4    | 
     3 4 5  |

     3 _ 5  | concatenation of full interval (1 -> i) with (i+1 -> n)
 ---------------------
       4    | full interval
       4 5  |

         5  | concatenation of full interval (breaks here)

那么,你要做的是:

1- 打印完整区间 from = 1to = n
2- 迭代连接两个带有“负”部分的区间
3- 再次调用传递 (from++, to)

的递归方法

希望对你有帮助

关于java - 使用递归打印所有数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107036/

相关文章:

java - 为什么我收到 "java.lang.ArrayIndexOutOfBoundsException: 0"

algorithm - 找到反向算法回到初始值

java - 为什么递归调用的不同位置的递归行为不同

javascript - 父值作为嵌套 javascript 对象中所有子值的总和

python - 递归,Python,计数,倒计时

java - 点击编辑文本android时出错

java - Android-通知没有出现

javax.net.ssl.SSLPeerUnverifiedException : peer not authenticated when trying to session. getPeerCertificateChain()

algorithm - 给定一棵二叉树,找到最大的子树,即二叉搜索树

c++ - 在并行桶排序中使用递归基数排序