This commit is contained in:
krahets
2023-10-08 01:43:28 +08:00
parent 3d2d669b43
commit baac2d11a7
52 changed files with 999 additions and 625 deletions
@@ -61,7 +61,7 @@ status: new
```csharp title="iteration.cs"
/* for 循环 */
int forLoop(int n) {
int ForLoop(int n) {
int res = 0;
// 循环求和 1, 2, ..., n-1, n
for (int i = 1; i <= n; i++) {
@@ -239,7 +239,7 @@ status: new
```csharp title="iteration.cs"
/* while 循环 */
int whileLoop(int n) {
int WhileLoop(int n) {
int res = 0;
int i = 1; // 初始化条件变量
// 循环求和 1, 2, ..., n-1, n
@@ -431,7 +431,7 @@ status: new
```csharp title="iteration.cs"
/* while 循环(两次更新) */
int whileLoopII(int n) {
int WhileLoopII(int n) {
int res = 0;
int i = 1; // 初始化条件变量
// 循环求和 1, 2, 4, 5...
@@ -636,8 +636,8 @@ status: new
```csharp title="iteration.cs"
/* 双层 for 循环 */
string nestedForLoop(int n) {
StringBuilder res = new StringBuilder();
string NestedForLoop(int n) {
StringBuilder res = new();
// 循环 i = 1, 2, ..., n-1, n
for (int i = 1; i <= n; i++) {
// 循环 j = 1, 2, ..., n-1, n
@@ -851,12 +851,12 @@ status: new
```csharp title="recursion.cs"
/* 递归 */
int recur(int n) {
int Recur(int n) {
// 终止条件
if (n == 1)
return 1;
// 递:递归调用
int res = recur(n - 1);
int res = Recur(n - 1);
// 归:返回结果
return n + res;
}
@@ -1055,12 +1055,12 @@ status: new
```csharp title="recursion.cs"
/* 尾递归 */
int tailRecur(int n, int res) {
int TailRecur(int n, int res) {
// 终止条件
if (n == 0)
return res;
// 尾递归调用
return tailRecur(n - 1, res + n);
return TailRecur(n - 1, res + n);
}
```
@@ -1237,12 +1237,12 @@ status: new
```csharp title="recursion.cs"
/* 斐波那契数列:递归 */
int fib(int n) {
int Fib(int n) {
// 终止条件 f(1) = 0, f(2) = 1
if (n == 1 || n == 2)
return n - 1;
// 递归调用 f(n) = f(n-1) + f(n-2)
int res = fib(n - 1) + fib(n - 2);
int res = Fib(n - 1) + Fib(n - 2);
// 返回结果 f(n)
return res;
}
@@ -1471,9 +1471,9 @@ status: new
```csharp title="recursion.cs"
/* 使用迭代模拟递归 */
int forLoopRecur(int n) {
int ForLoopRecur(int n) {
// 使用一个显式的栈来模拟系统调用栈
Stack<int> stack = new Stack<int>();
Stack<int> stack = new();
int res = 0;
// 递:递归调用
for (int i = n; i > 0; i--) {
@@ -1493,7 +1493,25 @@ status: new
=== "Go"
```go title="recursion.go"
[class]{}-[func]{forLoopRecur}
/* 使用迭代模拟递归 */
func forLoopRecur(n int) int {
// 使用一个显式的栈来模拟系统调用栈
stack := list.New()
res := 0
// 递:递归调用
for i := n; i > 0; i-- {
// 通过“入栈操作”模拟“递”
stack.PushBack(i)
}
// 归:返回结果
for stack.Len() != 0 {
// 通过“出栈操作”模拟“归”
res += stack.Back().Value.(int)
stack.Remove(stack.Back())
}
// res = 1+2+3+...+n
return res
}
```
=== "Swift"