이 문제는.. 조금 생각하다보니 재귀함수로 풀어야 겠단 생각이 들었다 .
package OneDayOneCodingChallenge;
import org.junit.Assert;
import org.junit.Test;
/**
* @author seoyeon on 2020/09/15
* @project AlgorithmTest
*/
public class Day12 {
public int solution(int[] numbers, int target) {
return DFS(numbers, target, 0, 0);
}
public int DFS(int[] numbers, int target, int index, int num) {
if (index == numbers.length) {
if (num == target) {
return 1;
}
return 0;
} else {
return DFS(numbers, target, index + 1, num + numbers[index])
+ DFS(numbers, target, index + 1, num - numbers[index]);
}
}
@Test
public void 정답() {
Assert.assertEquals(5, solution(new int[]{1, 1, 1, 1, 1}, 3));
}
}
'Algorithm' 카테고리의 다른 글
[알고리즘이론] 다이나믹 프로그래밍 (0) | 2020.09.28 |
---|---|
[프로그래머스]단어변환 (0) | 2020.09.20 |
[프로그래머스]위장 (0) | 2020.09.14 |
[프로그래머스]문자열 내 마음대로 정렬하기 (0) | 2020.09.11 |
[프로그래머스]다리 위를 지나는 트럭 (0) | 2020.09.10 |