728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43165
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음 문제를 읽었을 땐 어떻게 하는 거야.. 흑흑 이랬는데
정작 풀어보니까 쉬운 문제였다... 백트래킹으로 생각하면 쉬웠는데 (DFS나 백트래킹이나..)
숫자를 그대로 두고 +로 할거냐 -로 할 거냐를 선택하면서 진행하면 된다. DFS로 지금까지 계산한 값에 numbers의 수를 더할지(0) 뺄지(1)를 넘겨주면 된다. target과 결과가 동일하면 ans++
이런 형태의 코드를 볼때마다 내가 혼자 생각해내서 할 수 있을까 했는데
역시 문제는 많이 풀어봐야.. 혼자 작성할 수 있게 되는 거 같다!
후후 힘나는 문제군
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int ans = 0;
int calculate(int op1, int op2, int way){
if(way == 0) return op1+op2; //+
return op1-op2;
}
void DFS(int cnt, int k, int target, int value, vector<int> numbers){
if(cnt == k){
if(target == value) ans++;
return;
}
DFS(cnt+1, k, target, calculate(value, numbers[cnt], 0), numbers);
DFS(cnt+1, k, target, calculate(value, numbers[cnt], 1), numbers);
}
int solution(vector<int> numbers, int target) {
int answer = 0;
DFS(0, numbers.size(), target, 0, numbers);
answer = ans;
return answer;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// cout << solution({1,1,1,1,1}, 3) << '\n';
cout << solution({4,1,2,1}, 4) << '\n';
return 0;
}
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Lv1] 폰켓몬 (0) | 2022.08.09 |
---|---|
[프로그래머스/Lv2] 행렬의 곱셈 (0) | 2022.08.08 |
[프로그래머스/Lv2] 전력망을 둘로 나누기 (0) | 2022.08.07 |
[프로그래머스/Lv2] 피로도 (0) | 2022.08.07 |
[프로그래머스/Lv2] 소수 찾기 (0) | 2022.08.07 |