Home [Algorithm] Brute-force Search 2
Post
Cancel

[Algorithm] Brute-force Search 2

Brute-force Search


Task

Previous 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)
**/

The source : https://blog.naver.com/PostView.naver?blogId=seop1284&logNo=222450982972&parentCategoryNo=&categoryNo=9&viewDate=&isShowPopularPosts=true&from=search


Itโ€™s quite difficult! Letโ€™s resolve it afterwards.

This post is licensed under CC BY 4.0 by the author.

[Algorithm] Brute-force Search

[Algorithm] Brute-force Search 3

Comments powered by Disqus.