๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค[Java] - (Level2)ํƒ€๊ฒŸ๋„˜๋ฒ„(dfs)

by ์ฃผ๋ฐœ2 2020. 3. 30.
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/43165?language=java

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

์ฝ”๋“œ

class Solution {
    
    public static int answer = 0;
    
	public void dfs(int[] numbers, int target, int index){
		// base case:
		if(index == numbers.length){
			int sum = 0;
			for(int i=0; i<numbers.length; i++) 
				sum += numbers[i];

			answer += (sum == target) ? 1 : 0;  /* ํ•ฉ๊ณผ target์ด ๊ฐ™์œผ๋ฉด +1 ๋‹ค๋ฅด๋ฉด +0 */
			return;
		}

		dfs(numbers, target, index+1);	/* numbers๋ฐฐ์—ด ๋ชจ๋‘ ์‚ฌ์šฉํ•  ๋•Œ ๊นŒ์ง€ dfs ํƒ์ƒ‰ */
		numbers[index] *= -1;		/* ๋ชจ๋‘ ์‚ฌ์šฉ ํ›„ base case๋ฅผ ํ†ตํ•ด ํ•จ์ˆ˜ ์ข…๋ฃŒํ•˜๊ณ  ์ „๋‹จ๊ณ„๋กœ ๋Œ์•„๊ฐ€์„œ ์–‘์ˆ˜->์Œ์ˆ˜, ์Œ์ˆ˜->์–‘์ˆ˜ */
		dfs(numbers, target, index+1);	/* ์œ„์—์„œ ๋งŒ๋“  ์Œ์ˆ˜๋กœ ๋‹ค์‹œ ๋๊นŒ์ง€ dfs ํƒ์ƒ‰ */

	}
    
    public int solution(int[] numbers, int target) {
        dfs(numbers, target, 0);
        return answer;
    }
}

ํ’€์ด

๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ target ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ return,

๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ๋Š” ์—ฐ์‚ฐ๊ณผ์ •์„ Tree๋กœ ๋ณผ๋•Œ, '+'์—ฐ์‚ฐ์€ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ, '-'์—ฐ์‚ฐ์€ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ๋กœ ๋‚ด๋ ค๊ฐ€๋Š” ๊ณผ์ •์œผ๋กœ ์žฌ๊ท€ํ˜ธ์ถœ์„ ํ†ตํ•ด ํ•ด๊ฒฐํ•œ๋‹ค.(๊นŠ์ด์šฐ์„ ํƒ์ƒ‰, dfs)

๊ธฐ์ € ์‚ฌ๋ก€๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ(index == numbers.length) ์ด๋‹ค.

https://lkhlkh23.tistory.com/74

์œ„ ๊ณผ์ •์„ ์ž˜๋‚˜ํƒ€๋‚ธ ์ด๋ฏธ์ง€๊ฐ€ ์žˆ์–ด์„œ ์ฐธ๊ณ ํ–ˆ๋‹ค.

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€