mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 12:58:42 +08:00
feat(dart): add forLoopRecur and update HashMapOpenAddressing (#802)
* feat(dart): add forLoopRecur * feat(dart): update HashMapOpenAddressing
This commit is contained in:
@ -14,6 +14,25 @@ int recur(int n) {
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* 使用迭代模拟递归 */
|
||||
int forLoopRecur(int n) {
|
||||
// 使用一个显式的栈来模拟系统调用栈
|
||||
List<int> stack = [];
|
||||
int res = 0;
|
||||
// 递:递归调用
|
||||
for (int i = n; i > 0; i--) {
|
||||
// 通过“入栈操作”模拟“递”
|
||||
stack.add(i);
|
||||
}
|
||||
// 归:返回结果
|
||||
while (!stack.isEmpty) {
|
||||
// 通过“出栈操作”模拟“归”
|
||||
res += stack.removeLast();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 尾递归 */
|
||||
int tailRecur(int n, int res) {
|
||||
// 终止条件
|
||||
@ -43,6 +62,9 @@ void main() {
|
||||
res = tailRecur(n, 0);
|
||||
print("\n尾递归函数的求和结果 res = $res");
|
||||
|
||||
res = forLoopRecur(n);
|
||||
print("\n使用迭代模拟递归求和结果 res = $res");
|
||||
|
||||
res = fib(n);
|
||||
print("\n斐波那契数列的第 $n 项为 $res");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user