DFS 풀이
package com.company;
public class Solution {
static public void main(String[] args) {
int[] quiz1 = { 1, 1, 1, 1, 1 };
int quizTarget1 = 3;
int[] quiz2 = { 4, 1, 2, 1 };
int quizTarget2 = 4;
System.out.println(solution(quiz1, quizTarget1) == 5);
System.out.println(solution(quiz2, quizTarget2) == 2);
}
static char[] operators = {'+','-'};
static int[] numbers;
static public int solution(int[] quizNumbers, int target) {
int answer = 0;
numbers = quizNumbers;
int index = 0;
for (char operator : operators) {
answer += dfs(operator,index,target);
}
return answer;
}
private static int dfs(char op, int index, int quizTarget) {
int tempAnswer = 0;
if (op == '+') {
quizTarget = quizTarget - numbers[index];
} else {
quizTarget = quizTarget + numbers[index];
}
index++;
if (index != numbers.length) {
for (char operator : operators) {
tempAnswer += dfs(operator, index, quizTarget);
}
} else {
if (quizTarget == 0)
return 1;
else
return 0;
}
return tempAnswer;
}
}
BFS 풀이
package com.company;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
static public void main(String[] args) {
int[] quiz1 = { 1, 1, 1, 1, 1 };
int quizTarget1 = 3;
int[] quiz2 = { 4, 1, 2, 1 };
int quizTarget2 = 4;
System.out.println(solution(quiz1, quizTarget1) == 5);
System.out.println(solution(quiz2, quizTarget2) == 2);
}
static int[] numbers;
static public int solution(int[] quizNumbers, int target) {
int answer = 0;
numbers = quizNumbers;
int index = 0;
answer = bfs(index, target);
return answer;
}
private static int bfs(int index, int target) {
int tempAnswer = 0;
final int FINAL_INDEX = numbers.length - 1;
Queue<Number> queue = new LinkedList<Number>();
queue.add(new Number(numbers[index], index));
queue.add(new Number(-numbers[index], index));
while (!queue.isEmpty()) {
Number tempNumber = queue.poll();
if(tempNumber.index == FINAL_INDEX){
if (tempNumber.value == target) {
tempAnswer++;
}
}else{
tempNumber.index += 1;
queue.add(new Number(tempNumber.value + numbers[tempNumber.index], tempNumber.index));
queue.add(new Number(tempNumber.value - numbers[tempNumber.index], tempNumber.index));
}
}
return tempAnswer;
}
}
class Number {
int value;
int index;
public Number(int value, int index) {
this.value = value;
this.index = index;
}
}