Post

๐Ÿข 11. Recursion & Dynamic programming

โญ ๋ฌด์‹ํ•œ ๋ฐฉ๋ฒ• (brute force)

1
countWay(n-1) + countWays(n-2) + countWays(n-3)
  • ์ดˆ๊ธฐ ์‚ฌ๋ก€(base case) ์ค‘์š”ํ•จ
  • ํ˜„์žฌ ๋”›๊ณ  ์žˆ๋Š” ๊ณ„๋‹จ์ด 0๋ฒˆ์งธ ๊ณ„๋‹จ์ด๋ผ๊ณ  ํ•˜๋ฉด, ์—ฌ๊ธฐ๊นŒ์ง€๋Š” 0๊ฐœ์˜ ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š”๊ฑธ๊นŒ? 1๊ฐœ์˜ ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š”๊ฑธ๊ฐ€?
    • ์ •๋‹ต์€ ์ •์˜ํ•˜๊ธฐ ๋‚˜๋ฆ„
  • 1๋กœ ์ •์˜ํ•˜๋Š” ๊ฒƒ์ด ๋ฌธ์ œ ํ’€๊ธฐ ๋” ์‰ฝ๋‹ค
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    int countWays(int n) {
    	if (n < 0) {
    		return 0;
    	} else if (n == 0) {
    		return 1;
    	} else {
    		return countWays(n-1) + countWays(n-2) + countWays(n-3);
    	}
    }
    
    • ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์ˆ˜ํ–‰ ์‹œ๊ฐ„์€ ์ง€์ˆ˜์ ์œผ๋กœ ์ฆ๊ฐ€ํ•œ๋‹ค
    • ์žฌ๊ท€ ํ˜ธ์ถœ ์„ธ๋ฒˆ ํ•จ

โญ ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ๋ฐฉ๋ฒ•

  • countWays๊ฐ€ ๋ถˆํ•„์š”ํ•˜๊ฒŒ ์ค‘๋ณต ํ˜ธ์ถœ๋˜๋Š” ๊ฒฝ์šฐ ์žˆ์Œ
  • n์„ ์ด์ „์— ๋ณธ ์ ์ด ์žˆ๋‹ค๋ฉด ์บ์‹œ์— ์ €์žฅ๋œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ๋œ๋‹ค
  • ๊ฐ’์„ ์ƒˆ๋กœ ๊ณ„์‚ฐํ•  ๋•Œ๋งˆ๋‹ค ์ด๋ฅผ ์บ์‹œ์— ์ €์žฅํ•ด๋‘”๋‹ค
  • ์ผ๋ฐ˜์ ์œผ๋กœ ์บ์‹œ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ HashMap ์‚ฌ์šฉํ•จ
    • ํ‚ค ๊ฐ’์ด ์ •ํ™•ํ•˜๊ฒŒ 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ •์ˆ˜๊ฐ’์ด๋ฏ€๋กœ ์ •์ˆ˜ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ๊ณต๊ฐ„ ๋ฉด์—์„œ ๋” ํšจ์œจ์ ์ด๋‹ค

โญ ์—ฐ๊ด€ ๋ฌธ์ œ: ์ค‘๋ณต๋œ ๊ฐ’์„ ํ—ˆ์šฉํ•œ๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ’€๊ฒ ๋Š”๊ฐ€

  • ์›์†Œ๋“ค์ด ์ค‘๋ณต๋˜์–ด ๋‚˜ํƒ€๋‚˜๋ฉด ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ์ œ๋Œ€๋กœ ๋™์ž‘๋˜์ง€ ์•Š๋Š”๋‹ค
    • ํ•ด๋ฒ• 1: ์žฌ๊ท€
      • ์ดˆ๊ธฐ ์‚ฌ๋ก€๋กœ๋ถ€ํ„ฐ์˜ ํ™•์žฅ
      • ์ตœ์ ํ™”๋ฅผ ์›ํ•œ๋‹ค๋ฉด ์žฌ๊ท€๊ฐ€ ์•„๋‹Œ ๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉ
    • ํ•ด๋ฒ• 2: ์กฐํ•ฉ๋ก 
      • ์ง‘ํ•ฉ ์ƒ์„ฑํ•  ๋•Œ ์›์†Œ ๊ฐ๊ฐ์— ๋Œ€ํ•ด ๋‘ ๊ฐ€์ง€ ์ค‘ ํ•œ ๊ฐ€์ง€ ๊ฒฐ์ •ํ•ด์•ผ ํ•จ
      • ์ง‘ํ•ฉ์— ์†ํ•˜๋Š”์ง€ or ์†ํ•˜์ง€ ์•Š๋Š”์ง€
      • 2^n ๊ฐœ์˜ ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„ ์ง‘ํ•ฉ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค
This post is licensed under CC BY 4.0 by the author.