알고리즘 풀이/백준

[백준][Java] 2661번 좋은수열 (백트래킹)

배게 2021. 10. 5. 19:37
728x90

Line:19~21 부분에 isEnded boolean플래그를 빼고

System.out.exit(0)으로 해봤음 현재 프로세스를 아예 종료해버리는건데

이렇게 하니까 메모리 수행시간 둘 다 더 늘어났음

 

 

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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
 
public class Main {
    
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
 
    private static int N;
    private static boolean isEnded;
    
    private static void backTracking(StringBuilder curr) {
        int len = curr.length();
        if(len==N) {
            isEnded = true;
            System.out.println(curr.toString());
            return;
        }
        
        uLoop:
        for(int i=1; i<=3; i++) {
            StringBuilder temp = curr.append(i);
            int tempLen = temp.length();
            int l = tempLen/2;
            
            if(tempLen>=2) {
                while(true) {
//                    System.out.println(temp.substring(tempLen-l , tempLen));
//                    System.out.println(temp.substring(tempLen-2*l , tempLen-l));
                    
            if(temp.substring(tempLen-l , tempLen)
                            .equals(temp.substring(tempLen-2*l , tempLen-l))) {
                        curr.deleteCharAt(tempLen-1);
                        continue uLoop;
                    }
                    if(--l<=0break;
                }
            }
            backTracking(temp);
            if(isEnded) return;
            curr.deleteCharAt(tempLen-1);
        }
        
    }
    
    public static void main(String[] args) throws IOException{
        N = stoi(br.readLine());
        
        backTracking(new StringBuilder());
        
//        bw.flush();
//        bw.close();
    }
    
 
    private static int stoi(String input) {
        return Integer.parseInt(input);
    }
}
cs