Câu hỏi phỏng vấn Recursion
Câu hỏi

What is a good example of Recursion (other than generating a Fibonacci sequence)?

Câu trả lời

Here are some good examples of recursion other than generating the Fibonacci sequence:

Towers of Hanoi

The Towers of Hanoi is a classic recursion problem. The goal is to move a stack of discs from one pole to another, following these rules:

  1. Only one disc can be moved at a time
  2. Each move consists of taking the upper disc from one of the stacks and placing it on top of another stack or an empty pole
  3. No disc may be placed on top of a smaller disc

To solve this recursively:

  1. Move the top n-1 discs from the source pole to the auxiliary pole
  2. Move the remaining disc from the source pole to the destination pole
  3. Move the n-1 discs from the auxiliary pole to the destination pole[1][4]

Factorial

The factorial of a number n is the product of all positive integers less than or equal to n. It can be defined recursively as:

Copy
factorial(n) = 1                  if n = 0
             = n * factorial(n-1) if n > 0

So the factorial of 5 would be calculated recursively as:

Copy
factorial(5) = 5 * factorial(4)
             = 5 * 4 * factorial(3) 
             = 5 * 4 * 3 * factorial(2)
             = 5 * 4 * 3 * 2 * factorial(1)
             = 5 * 4 * 3 * 2 * 1 = 120
```[2][4]

## Palindrome Checker

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. A recursive palindrome checker can be implemented by:

1. Co...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Is it always possible to write a non-recursive form for every Recursive function?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào