gpt4 book ai didi

java - 递归到非递归,现在困扰我一段时间

转载 作者:行者123 更新时间:2023-12-01 13:20:29 26 4
gpt4 key购买 nike

F(n): 
if n >= 6:
F(n/3)
F(2*n/3)
print n

我如何将其转换为非递归函数?我尝试使用两个 while 循环,一个用于 n/3 案例,另一个用于 2*n/3 案例,但没有输出正确的东西
public static void F2Stack(int n) {
Stack stack2 = new Stack();
int current = n;
int current2 = n;
while(current >= 6) {
current = current/3;
stack2.push(current);
}
while(current2 >= 6) {
current2 = current2*2/3;
stack2.push(current2/3);
stack2.push(current2*2/3);
stack2.push(current2);
}
while(!(stack2.isEmpty())){
System.out.println(stack2.pop());
}

}

最佳答案

该死的冠状病毒封锁!今天花了四五个小时,但我们得到了一些东西。我猜最困难的部分是 java 无法执行“转到标签”。只有您可以执行“继续/中断标签”。无论如何希望这对某人有所帮助;

 public static void main(String[] args) {

System.out.println("vvvv 18 recursive vvvv");
recursive(18);
System.out.println("vvvv 18 nonrecursive vvvv");
nonRecursive(18);

System.out.println("vvvv 25 recursive vvvv");
recursive(25);
System.out.println("vvvv 25 nonrecursive vvvv");
nonRecursive(25);

System.out.println("vvvv 31 recursive vvvv");
recursive(25);
System.out.println("vvvv 31 nonrecursive vvvv");
nonRecursive(25);



}

static void doJob(int n) {
System.out.println(n);
}

static void recursive(int number) {
if (number >= 6) {
recursive(number/3);
recursive(2*number/3);
}
doJob(number);
}

static void nonRecursive(int number) {

// a basic context
class Ctx {

int n, m;
boolean bn, bm;

public Ctx(int num) {
n = num / 3;
// do not try m = 2 * n :)
m = 2 * num / 3;
}

};

// how many times can we change the context?
// we will use here a bit math
int d = 2 * ((int)(Math.log(2 * number)/Math.log(3)) + 1);
Ctx[] ctx = new Ctx[d];

// current context
ctx[0] = new Ctx(number);
int i = 0;
while (number >= 6 && ctx[0] != null) {

// do n/3
if (ctx[i].n >= 6 && !ctx[i].bn) {
i++;
ctx[i] = new Ctx(ctx[i-1].n);
continue;
}

// we reached as deep as poosible for n/3
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
}

// now do 2*n/3
if (ctx[i].m >= 6 && !ctx[i].bm) {
i++;
ctx[i] = new Ctx(ctx[i-1].m);
continue;
}

if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}

// we are done with this context
ctx[i] = null;
if (i > 0) {
i--;
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
} else if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}
}

}

doJob(number);

}

关于java - 递归到非递归,现在困扰我一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60142293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com