일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 시스템프로그래밍
- 공부기록
- 협업도구
- Django
- 코딩테스트
- 회고록
- 코테
- java
- 기술블로그
- github
- 자바
- 트러블슈팅
- IT
- 백준
- kafkaconsumer
- 문자열압축
- 문자열함수
- 기록
- AWS
- 자료구조
- 선택정렬
- git
- jwt
- SpringSecurity
- 한이음
- c
- testcode
- kafka
- codingtest
- 알고리즘
Archives
- Today
- Total
신뇽이 되어보자
[프로그래머스] 소수 찾기 (dfs) 본문
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/42839
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
import java.util.*;
class Solution {
public boolean[] visited = new boolean[7];
public Set<Integer> set;
public int solution(String numbers) {
int answer = 0;
set = new HashSet<>(); //중복을 피해야하기 때문
dfs(numbers, "",0);
for(int num: set){
if(isPrime(num)){
answer +=1;
}
}
return answer;
}
public void dfs(String numbers, String str, int len){
if(len > numbers.length()){
return;
}
for(int i = 0; i< numbers.length(); i++){
if(!visited[i]){ //방문한 적이 없으면
visited[i] = true;
set.add(Integer.parseInt(str + numbers.charAt(i))); //추가를 하고
dfs(numbers, str + numbers.charAt(i), len + 1); // 길이 올려주기
visited[i] = false; //다음꺼 해줘야하니까 백트래킹
}
}
}
public boolean isPrime(int num){
if(num < 2){
return false;
}
for(int i = 2; i<num; i++){
if(num % i == 0){
return false;
}
}
// 에라토스테네스 체
// for (int i = 2; i <= (int) Math.sqrt(n); i++) {
// if (n % i == 0) {
// return false;
// }
// }
return true;
}
}
728x90
'CodingTest' 카테고리의 다른 글
[프로그래머스] 주사위 게임 3 (1) | 2025.02.24 |
---|---|
[프로그래머스] 배열 조작하기(Arrays.copyOfRange) (1) | 2025.02.24 |
[프로그래머스] 전력망을 둘로 나누기 (양방향 그래프, dfs) (1) | 2025.02.23 |
[프로그래머스] 카펫 (완탐) (0) | 2025.02.22 |
[프로그래머스] 피로도 자바 (백트래킹, dfs) (1) | 2025.02.22 |