프로그래머스 | 타겟넘버 | DFS, BFS
Algorithm 2019. 8. 26. 16:48문제 설명
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.
-1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3
사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.
제한사항
- 주어지는 숫자의 개수는 2개 이상 20개 이하입니다.
- 각 숫자는 1 이상 50 이하인 자연수입니다.
- 타겟 넘버는 1 이상 1000 이하인 자연수입니다.
입출력 예
numberstargetreturn
[1, 1, 1, 1, 1] | 3 | 5 |
입출력 예 설명
문제에 나온 예와 같습니다.
1
2
3
4
5
6
7
8
|
using System;
public class Solution {
public int solution(int[] numbers, int target) {
int answer = 0;
return answer;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
using System;
using System.Collections.Generic;
namespace _21
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("타겟넘버");
int[] numbers = {1, 1, 1, 1, 1};
int target = 3;
//result: 5
var sol = new Solution();
var result = sol.solution(numbers, target);
Console.WriteLine("result: {0}", result);
}
}
public class Solution {
private int target;
public int solution(int[] numbers, int target) {
this.target = target;
return DFS(numbers, 0, 0);
}
private int DFS(int[] numbers, int idx, int count){
return count == this.target ? 1 : 0;
}else{
return DFS(numbers, idx + 1, count + numbers[idx]) +
DFS(numbers, idx + 1, count - numbers[idx]);
}
}
}
}
|
'Algorithm' 카테고리의 다른 글
프로그래머스 | 타겟넘버 (0) | 2019.08.27 |
---|---|
TODO | 프로그래머스 | 네트워크 | DFS/BFS (0) | 2019.08.27 |
TODO | 프로그래머스 | 점프와 순간이동 (0) | 2019.08.26 |
프로그래머스 | 조이스틱 | 그리디 알고리즘 (0) | 2019.08.26 |
프로그래머스 | JadenCase 문자열 만들기 (0) | 2019.08.26 |