본문 바로가기

Algorithm

[프로그래머스]타켓 넘버

이 문제는.. 조금 생각하다보니 재귀함수로 풀어야 겠단 생각이 들었다 . 

 

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));
  }
}