如何将嵌套循环转换为递归?附JavaScript代码示例求实现方案
Got it, let's break down how to turn that nested loop into recursion step by step. The original code runs an outer loop for i from 0 to 4, and for each i, it runs an inner loop for j from 0 to 4, logging each pair. Here's how to replicate that behavior with recursion, in a couple of straightforward ways:
Method 1: Separate Recursive Functions for Outer and Inner "Loops"
This approach mirrors the original nested loop structure closely by splitting the logic into two recursive functions—one handling the outer i sequence, and the other handling the inner j sequence for each i:
// Inner recursion: handles the j iteration for a given i function innerRecursion(i, j) { // Termination condition: stop when j reaches 5 if (j >= 5) return; console.log(i, j); // Recurse with j incremented by 1 innerRecursion(i, j + 1); } // Outer recursion: handles the i iteration function outerRecursion(i) { // Termination condition: stop when i reaches 5 if (i >= 5) return; // Run the inner recursion for the current i, starting j at 0 innerRecursion(i, 0); // Recurse with i incremented by 1 outerRecursion(i + 1); } // Start the recursion with i=0 outerRecursion(0);
How it works:
outerRecursionstarts ati=0and callsinnerRecursionto handle alljvalues for thati.- Once
innerRecursionfinishes (whenj >=5),outerRecursionincrementsiand repeats the process untili >=5.
Method 2: Single Recursive Function for Both Iterations
If you prefer a single function, you can handle both i and j in one place by checking which iteration needs to progress:
function nestedRecursion(i, j) { // Terminate the entire process if i has reached 5 if (i >= 5) return; if (j < 5) { // Still in the inner j loop: log the pair and increment j console.log(i, j); nestedRecursion(i, j + 1); } else { // Inner loop done for current i: move to next i, reset j to 0 nestedRecursion(i + 1, 0); } } // Start with i=0, j=0 nestedRecursion(0, 0);
How it works:
- The function first checks if we've exhausted all
ivalues (termination condition). - If
jis still within bounds, it logs the pair and recurses withj+1. - When
jhits 5, it switches to the nextiand resetsjto 0, continuing the recursion.
Both methods will produce exactly the same output as your original nested loop: every pair (0,0) through (4,4) logged in order.
内容的提问来源于stack exchange,提问作者Dhruv

