作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
F(n):
if n >= 6:
F(n/3)
F(2*n/3)
print n
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/
很难理解 ownerdraw TreeView ,这里是完整的故事: 一个 VS2013 WinForms 应用程序(在 Windows 8.1 上运行,如果重要的话启用了 TrueType ....
我有以下 JSON 数据,其中包含一个 nations 数组。数据 JSON 文件中的 Neighbouring 指示哪些国家与其他国家有邻居。国家的id指的是邻国的id。 即。俄罗斯与乌克兰相邻,波
有两个表,一个 Contact 表和一个 RelationshipHistory 表。 联系人可以具有多种类型的关系(业务、个人、志愿者等),这意味着随着时间的推移,他们可以在Relationship
我是一名优秀的程序员,十分优秀!