Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 플로이드-와샬
- 백준
- 에라토스테네스의 체
- CS
- 완전탐색
- 문자열
- Effective Java
- 프로그래머스
- 스택
- 위상정렬
- 세그먼트 트리
- 백트래킹
- 유니온 파인드
- swea
- 투 포인터
- 후니의 쉽게 쓴 시스코 네트워킹
- 그리디
- mst
- java
- 이분탐색
- 구현
- 동적계획법
- Network
- Kotlin
- 수학
- BFS
- 시뮬레이션
- 알고리즘
- dfs
- JUnit 5
Archives
반갑습니다!
[프로그래머스] N으로 표현 본문
동적계획법으로 분류되어있지만 당장 생각나지 않고 N의 값이 작아서 완전 탐색으로 해결하였다.
풀이
DFS를 통해 N ~ NNNNNNNN 까지 생성하여 사칙연산을 반복하여 number
가 될 떄까지 탐색한다.
코드
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int num, ans = 9;
void dfs(int N, int cnt, int cur){
if(cnt >= 9) return;
if(num == cur){
ans = min(ans, cnt);
return;
}
int tmp = 0;
for(int i=0; i+cnt<9; i++){
tmp = 10 * tmp + N;
dfs(N, i+cnt+1, cur + tmp);
dfs(N, i+cnt+1, cur - tmp);
dfs(N, i+cnt+1, cur * tmp);
dfs(N, i+cnt+1, cur / tmp);
}
}
int solution(int N, int number) {
num = number;
dfs(N, 0, 0);
ans = ans == 9 ? -1 : ans;
return ans;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 가장 먼 노드 (0) | 2020.04.02 |
---|---|
[프로그래머스] 2 x n 타일링 (0) | 2020.04.02 |
[백준] 6198 옥상 정원 꾸미기 (0) | 2020.04.02 |
[백준] 2493 탑 (0) | 2020.04.02 |
[프로그래머스] 종이접기 (0) | 2020.03.31 |