알고리즘/Programmers

[프로그래머스/level2] 타겟넘버

스푼앤포크 2019. 11. 21. 12:17

타겟 넘버[DFS/BFS]

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 이하인 자연수입니다.

입출력 예

 

numbers target return
[1, 1, 1, 1, 1] 3 5

입출력 예 설명

문제에 나온 예와 같습니다.

 

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
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int final;
vector<int> arr;
int cnt=0;
int a=0;
void print(){
    for(int i=0; i<arr.size();i++){
        cout<<arr[i]<<" ";
    }
    cout<<"\n";
}
void dfs(int idx,int sum){
    int size = arr.size();
    if(idx>=size){
        //a++;
        if(sum == final)cnt++;
        return;
    }
        dfs(idx+1,sum + arr[idx]);
        dfs(idx+1,sum - arr[idx]);
}
int solution(vector<int> numbers, int target) {
    //copy
    arr.resize(numbers.size());
    for(int i=0; i<numbers.size();i++){
        arr[i] = numbers[i];
    }
    final = target;
    dfs(0,0);
    int answer = cnt;
    //cout<<a;
    return answer;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter




|본 포스팅은 쿠팡 파트너스의 일환으로 소정의 수수료를 제공받을 수 있음을 알립니다 |