์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ์žฌ๊ท€ ์šฉ๋ฒ• (recursive call, ์žฌ๊ท€ ํ˜ธ์ถœ)

jjingle 2024. 1. 30. 16:53

์žฌ๊ท€ ์šฉ๋ฒ•(recursive call) ?

- ํ•จ์ˆ˜ ์•ˆ์—์„œ ๋™์ผํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ํ˜•ํƒœ
- ์—ฌ๋Ÿฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์—์„œ ์‚ฌ์šฉ

 

 

์žฌ๊ท€ํ˜ธ์ถœ์˜ ์ผ๋ฐ˜์ ์ธ ํ˜•ํƒœ

  • ๋‚ด๋ถ€์ ์œผ๋กœ ์Šคํƒ(Stack)์ฒ˜๋Ÿผ ๊ด€๋ฆฌ๋œ๋‹ค
#case1
def function(์ž…๋ ฅ):
  if ์ž…๋ ฅ > ์ผ์ • ๊ฐ’:  # ์ž…๋ ฅ์ด ์ผ์ • ๊ฐ’ ์ด์ƒ์ด๋ฉด
    return function(์ž…๋ ฅ - 1) # ์ž…๋ ฅ ๊ฐ’๋ณด๋‹ค ์ž‘์€ ๊ฐ’
  else:
    return ์ผ์ • ๊ฐ’, ์ž…๋ ฅ ๊ฐ’, ๋˜๋Š” ํŠน์ • ๊ฐ’  # ์žฌ๊ท€ํ˜ธ์ถœ ์ข…๋ฃŒ
    
#case2
def function(์ž…๋ ฅ):
  if ์ž…๋ ฅ <= ์ผ์ • ๊ฐ’:  # ์ž…๋ ฅ์ด ์ผ์ • ๊ฐ’๋ณด๋‹ค ์ž‘์œผ๋ฉด
    return ์ผ์ • ๊ฐ’, ์ž…๋ ฅ ๊ฐ’, ๋˜๋Š” ํŠน์ • ๊ฐ’  # ์žฌ๊ท€ํ˜ธ์ถœ ์ข…๋ฃŒ
  
  funtion(์ž…๋ ฅ๋ณด๋‹ค ์ž‘์€ ๊ฐ’)
  return ๊ฒฐ๊ณผ ๊ฐ’