📘
Grokking-Algorithms book
PostgreSQL
  • Content
  • Introduction to Algorithms
    • Introduction
    • Binary Search
    • Big O notation
    • Recap
  • Selection sort
    • How memory works
    • Arrays and linked lists
    • Selection sort
    • Recap
  • Recursion
    • Recursion
    • Base case and recursive case
    • The stack
    • Recap
  • Quicksort
    • Divide & conquer
    • Quicksort
    • Big O notation revisited
    • Recap
  • Hash tables
    • Hash functions
    • Use cases
    • Collisions
    • Performance
    • Recap
  • Breadth-first search
    • Introduction to graph
    • What is a graph
    • Breadth-first search
    • Implementing the graph
    • Implementing the algorithm
    • Recap
  • Dijkstra's algorithm
    • Working with Dijkstra's algorithm
    • Terminology
    • Trading for a piano
    • Negative-weight edges
    • Implementation
    • Recap
  • Greedy Algorithms
    • The classroom scheduling problem
    • The knapsack problem
    • The set-covering problem
    • NP-complete problems
    • Traveling salesperson, step by step
    • Recap
  • Dynamic programming
    • The knapsack problem
    • Knapsack problem FAQ
    • Longest common substring
    • Recap
  • K-nearest neighbors
    • Classifying oranges vs. grapefruit
    • Building a recommendations system
    • Introduction to machine learning
    • Recap
  • Where to go next
    • Trees
    • Inverted indexes
    • The Fourier transform
    • Parallel algorithms
    • MapReduce
    • Bloom filters and HyperLogLog
    • The SHA algorithms
    • Locality-sensitive hashing
    • Diffie-Hellman key exchange
    • Linear programming
    • Epilogue
  • Answers to exercises
    • Chapter 1
    • Chapter 2
    • Chapter 3
    • Chapter 4
    • Chapter 5
    • Chapter 6
    • Chapter 7
    • Chapter 8
    • Chapter 9
    • Chapter 10
Powered by GitBook
On this page
  • Python
  • Golang
  • Python
  • Golang

Was this helpful?

Edit on GitHub
  1. Recursion

Recursion

PreviousRecursionNextBase case and recursive case

Last updated 1 year ago

Was this helpful?

Aytaylik, siz buvingizning chodirini qazib o'tiryapsiz va sirli qulflangan chamadonga duch keldingiz.

Buvim sizga chamadonning kaliti shu boshqa qutida bo'lishi mumkinligini aytadi.

Ushbu qutida ko'proq qutilar mavjud, ular ichida ko'proq qutilar mavjud. Kalit qayerdadir qutida. Kalitni qidirish algoritmingiz qanday? O'qishni davom ettirishdan oldin algoritm haqida o'ylab ko'ring.

Mana bitta yondashuv

  1. Ko'rish uchun qutilar to'plamini yarating.

  2. Bir qutini oling va uni ko'rib chiqing.

  3. Agar quti topsangiz, keyinroq ko'rib chiqish uchun uni qoziqqa qo'shing.

  4. Agar kalit topsangiz, ish tugadi!

  5. Takrorlang.

Mana muqobil yondashuv.

  1. Qutini ko'rib chiqing.

  2. Agar quti topsangiz, 1-bosqichga o'ting.

  3. Agar kalit topsangiz, ish tugadi!

Qaysi yondashuv sizga osonroq tuyuladi? Birinchi yondashuv while tsiklidan foydalanadi. Qoziq bo'sh bo'lmasa-da, qutini oling va uni ko'rib chiqing:

Python

def look_for_key(main_box):
    pile = main_box.make_a_pile_to_look_through()
    while pile is not empty:
        box = pile.grab_a_box()
        for item in box:
            if item.is_a_box():
                pile.append(item)
            elif item.is_a_key():
                print "found the key!"

Golang

func lookForKey(mainBox *Box) {
    
    pile := mainbox.MakeAPileToLookThrough()

    for pile != nil {
        box := pile.GrapABox()
        for item := range box {
            if item.IsABox() {
                pile.Append(item)
            } else if item.IsAKey() {
                fmt.Println("found the key!")
            }
        }
    }
}

Ikkinchi usul rekursiyadan foydalanadi. Rekursiya - funksiya o'zini chaqiradigan joy. Mana psevdokodning ikkinchi usuli:

Python

def look_for_key(box):
    for item in box:
        if item.is_a_box():
            look_for_key(item) # <--- RECURSION
        elif item.is_a_key():
            print "found the key!"

Golang

func lookForKey(box *Box) {
    for item := range box {
        if item.IsABox() {
            lookForKey(item) // <--- RECURSION
        } else if item.IsAKey() {
            fmt.Println("found the key!")
        }
    }
}

Ikkala yondashuv ham bir xil narsani amalga oshiradi, ammo ikkinchi yondashuv men uchun aniqroq. Rekursiya yechimni aniqroq qilganda ishlatiladi. Rekursiyadan foydalanishning unumdorligi yo'q; aslida, looplar ba'zan ishlash uchun yaxshiroqdir. Menga Ley Kolduellning Stack Overflow haqidagi ushbu iqtiboslari yoqadi: "Looplar dasturingiz uchun unumdorlikni oshirishi mumkin. Rekursiya dasturchingiz uchun unumdorlikka erishishi mumkin. Vaziyatingizda qaysi biri muhimroq ekanini tanlang!" 1

Ko'pgina muhim algoritmlar rekursiyadan foydalanadi, shuning uchun kontseptsiyani tushunish muhimdir.

1*

link
Suitcase
Nested boxes
Plan
Alternative approach
Python code
Recursion approach