所以我在我的计算机算法课上有这个作业: 编写一个递归算法,给定一个正整数 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 = 1
和 to = n
2- 迭代连接两个带有“负”部分的区间
3- 再次调用传递 (from++, to)
希望对你有帮助
关于java - 使用递归打印所有数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107036/