Brute-force Search
Task
2. ์์ ์ฐพ๊ธฐ in Programmers (Level 2)
๐ Problem
https://programmers.co.kr/learn/courses/30/lessons/42839
๐ The point
Use backtracking (dfs -> recursion)
๐ 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// backtracking -> use recursion
import java.util.List;
import java.util.ArrayList;
class Solution {
private boolean[] checked;
private List<Integer> nums;
public int solution(String numbers) {
int answer = 0;
nums = new ArrayList<>();
checked = new boolean[numbers.length()]; // string.length()
for (int i = 1; i <= numbers.length(); i++)
dfs(numbers, i, ""); // ์๋ฆฌ์ ์ฆ๊ฐ์ํค๊ธฐ
for (int i = 0; i < nums.size(); i++)
if (isPrimeNum(nums.get(i))) answer++;
return answer;
}
private void dfs(String numbers, int len, String tmp) {
if (tmp.length() == len) {
int n = Integer.parseInt(tmp);
if (!nums.contains(n)) nums.add(n);
return;
}
for (int i = 0; i < numbers.length(); i++) {
if (!checked[i]) {
tmp += numbers.charAt(i);
checked[i] = true;
dfs(numbers, len, tmp);
tmp = tmp.substring(0, tmp.length() - 1);
checked[i] = false;
}
}
}
private boolean isPrimeNum(int n) {
// case1. 0 or 1
if (n == 0 || n == 1) return false;
// case2. it can be divided with other number
for (int i = 2; i < n; i++)
if (n % i == 0) return false;
return true;
}
}
/**
[Question]
- make primary number by using numbers(string)
** what is primary number?
: the number can be only divided with 1 and itself.
[Condition]
- numbers : length = 1 ~ 7 (value = 0 ~ 9)
**/
Itโs quite difficult! Letโs resolve it afterwards.
Comments powered by Disqus.