使用递归查找系列

时间:2018-01-11 13:18:21

标签: java recursion

我正在尝试使用递归打印122333221,如果n是3.但是我无法解决它。我们已经给出了使用递归打印系列的数字。例如,如果n = 3那么它应该打印122333221

public static void print(int n){
if(n < 1 ){
  return;
}

print(n-1);
for(int i = 1; i <= n; i++){
    System.out.print(n);
}

}

public static void main(String[] args) {
print(3);

}

3 个答案:

答案 0 :(得分:3)

您必须使用通过参数跟踪状态的常规技术,方法是定义public方法,该方法使用带有额外参数的private方法。

// Repeats n n times.
private static void repeat(int n) {
    for (int i = 0; i < n; i++) {
        System.out.print(n);
    }
}

private static void print(int n, int v) {
    if (n == v) {
        // Just once for the deepest level.
        repeat(n);
    } else {
        // Wrap the inner print ...
        repeat(n);
        // Recurse with the next higher value.
        print(n + 1, v);
        // ... end the wrap.
        repeat(n);
    }
}

public static void print(int n) {
    System.out.print(n+": ");
    print(1, n);
    System.out.println();
}

public void test(String[] args) {
    for (int i = 1; i <= 9 ; i++) {
        print(i);
    }
}

答案 1 :(得分:0)

一个可能的解决方案是n是你拥有的不同数字的数字,而你需要打印每个数字乘以其值,所以如果n = 1

result = 1

n = 2结果1221

n = 3,结果122333221

n = 4,结果1223334444333221

实现并不难,基本情况是数字= n及其打印n次,除非你达到n,否则你总是递归打印,第一次调用总是

solve(n, 1,1);

实施:

public void solve(int n, int numberOfPrints, int  num) {

if(numberOfPrints == 0 && n ==num )
return ;
if(numberOfPrints == 0 )
   solve(n, num+1,num+1);

System.out.print(num);
solve(n, numberOfPrints-1, num);
if(num == n)
return;
System.out.print(num);
}

答案 2 :(得分:0)

public static void PrintSeries(int seriesNum, int currentNum, bool movingForward)
{
       if(movingForward && currentNum < seriesNum)
       {

                 PrintNum(currentNum);
                 PrintSeries(seriesNum, currentNum + 1, true); 

       }
       else if(movingForward && currentNum == seriesNum)
       {

                 PrintNum(currentNum);
                 PrintSeries(seriesNum, currentNum - 1, false); 
       }
       else
       {
            if(currentNum > 0)
            {
                 PrintNum(currentNum);
            }

            if(currentNum - 1 > 0)
            {

                PrintSeries(seriesNum, currentNum - 1, false); 
            }
       }

}

public static void PrintNum(int num)
{
       for(int x = 0; x < num; x++)
       {
           System.out.print(num);
       }

}