ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Algorithm] ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด ๊ตฌํ˜„
    ๐Ÿ’ปProgramming/Algorithm 2024. 4. 11. 17:34

    ๋ฌธ์ œ

    1) ํ”ผ๋ณด๋‚˜ํ‚ค ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค. ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์ด๋ž€ ์•ž์˜ 2๊ฐœ์˜ ์ˆ˜๋ฅผ ํ•ฉํ•˜์—ฌ ๋‹ค์Œ ์ˆซ์ž๊ฐ€ ๋˜๋Š” ์ˆ˜์—ด์ด๋‹ค.

    2) ์ž…๋ ฅ์€ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์˜ ์ด ํ•ญ์˜ ์ˆ˜ ์ด๋‹ค. ๋งŒ์•ฝ 7์ด ์ž…๋ ฅ๋˜๋ฉด 1 1 2 3 5 8 13์„ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

     

    ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๊ตฌํ˜„

    import java.util.Scanner;
    
    public class Section7_4_Ver1 {
        public static int DFS(int n) {
            if (n == 1 || n == 2)    return 1;
            else  return DFS(n - 2) + DFS(n - 1);
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            for (int i = 1; i <= n; i++) System.out.print(DFS(i) + " ");
        }
    }

    ๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•ด ์ถœ๋ ฅํ•œ๋‹ค. ์ด๋ ‡๊ฒŒ ๋˜๋ฉด ๋งค ์ˆซ์ž๋ฅผ ์ถœ๋ ฅํ•  ๋•Œ๋งˆ๋‹ค 1๋ถ€ํ„ฐ ๋‹ค์‹œ ์žฌ๊ท€๋ฅผ ์‹œ์ž‘ํ•ด์•ผํ•˜๋Š” ์น˜๋ช…์ ์ธ ๋‹จ์ ์ด ์žˆ๋‹ค. ํ•œ 45๊นŒ์ง€๋งŒ ๊ฐ€๋„ ๊ต‰์žฅํžˆ ์˜ค๋žœ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฐ๋‹ค. ๊ทธ๋ž˜์„œ ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ์‚ฌ์šฉํ•œ ์žฌ๊ท€ํ•จ์ˆ˜ ๊ตฌํ˜„์„ ํ†ตํ•ด ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ์‚ฌ์šฉํ•œ ๊ตฌํ˜„

    import java.util.Scanner;
    
    public class Section7_4_Ver2 {
        static int[] memo;
    
        public static int DFS(int n) {
            if (memo[n] != 0)   return memo[n];
            if (n <= 2) return memo[n] = 1;
            else return memo[n] = DFS(n - 2) + DFS(n - 1);
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            memo = new int[n + 1];
            DFS(n);
            for (int i = 1; i <= n; i++) System.out.print(memo[i] + " ");
        }
    }

    ์ค‘์š”ํ•œ ํฌ์ธํŠธ: memo[n]์— ๊ฐ’์ด ์žˆ๋‹ค๋ฉด, memo[n]์„ return ํ•œ๋‹ค. 

    ์œ„์˜ ์‚ฌ์ง„์„ ๋ณด๋ฉด DFS(3)์—์„œ ๋จผ์ € DFS(2)๋ฅผ ๊ตฌํ–ˆ๋Š”๋ฐ ๋˜ DFS(4)์—์„œ DFS(2)๊ฐ€ ํ•œ ๋ฒˆ ๋” ํ˜ธ์ถœ๋˜์–ด์•ผํ•œ๋‹ค. 

    ๋˜, DFS(4)์—์„œ DFS(3)์ด ๋จผ์ € ํ˜ธ์ถœ ๋˜์—ˆ๋Š”๋ฐ, ๋˜ DFS(5)์—์„œ DFS(3)์„ ํ˜ธ์ถœํ•œ๋‹ค. ์ด๋ ‡๊ฒŒ ๋˜๋ฉด 3์€ ๋˜ ํ•œ ๋ฒˆ ์žฌ๊ท€๋ฅผ ๋ฐ˜๋ณตํ•ด์•ผํ•œ๋‹ค.

    ๋จ„์•ฝ ์ˆ˜๊ฐ€ ์ปค์ง„๋‹ค๋ฉด ์ •๋ง ์—„์ฒญ๋‚œ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆด๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ฏธ ๋ฐฐ์—ด์— ์žˆ๋Š” ๊ฐ’์ด๋ผ๋ฉด ๊ทธ ๊ฐ’์„ returnํ•˜๋„๋ก ํ•˜๋Š”๊ฒƒ์ด ๋งค์šฐ ์ค‘์š”ํ•˜๋‹ค!

Designed by Tistory.