-
4-7: 좋은 수열Recursion 2018. 10. 24. 20:19
좋은 수열 (goodseq.cpp)
문제
숫자 1, 2, 3으로만 이루어지는 수열이 있다. 임의의 길이의 인접한 두 개의 부분 수열이 동일한 것 이 있으면, 그 수열을 나쁜 수열이라고 부른다. 그렇지 않은 수열은 좋은 수열이다.
다음은 나쁜 수열의 예이다.
33
32121323
123123213
다음은 좋은 수열의 예이다.
2
32
32123
1232123
길이가 N인 좋은 수열들을 N자리의 정수로 보아 그중 가장 작은 수를 나타내는 수열을 구하는 프로그램 을 작성하라. 예를 들면, 1213121과 2123212는 모두 좋은 수열이지만 그 중에서 작은 수를 나타내는 수 열 1213121이다.
입력
입력은 숫자 N하나로 이루어진다. N은 1 이상 80 이하이다.
출력
첫 번째 줄에 1, 2, 3으로만 이루어져 있는 길이가 N인 좋은 수열들 중에서 가장 작은 수를 나타내 는 수열만 출력한다. 수열을 이루는 1, 2, 3들 사이에는 빈칸을 두지 않는다.
예제 입력
7
예제 출력
1213121
import java.util.Scanner;
public class GoodSeq {
/**
*
* 숫자 1, 2, 3으로만 이루어지는 수열이 있다.
* 임의의 길이의 인접한 두 개의 부분 수열이 동일한 것 이 있으면, 그 수열을 나쁜 수열이라고 부른다.
* 그렇지 않은 수열은 좋은 수열이다.
*
* 다음은 나쁜 수열의 예이다.
*
* 33
*
* 32121323
*
* 123123213
*
* 다음은 좋은 수열의 예이다.
*
* 2
*
* 32
*
* 32123
*
* 1232123
*
* 길이가 N인 좋은 수열들을 N자리의 정수로 보아 그중 가장 작은 수를 나타내는 수열을 구하는 프로그램 을 작성하라.
* 예를 들면, 1213121과 2123212는 모두 좋은 수열이지만 그 중에서 작은 수를 나타내는 수 열 1213121이다.
*
* 7
*
* 1213121
*
*
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String combinations = "";
int[] count = new int[1];
printGoodSeqs(count, combinations, N);
}
private static void printGoodSeqs(int[] count, String combinations, int len) {
if (isGoodSequence(combinations)) {
if (combinations.length() ==0 ){
printGoodSeqs(count, combinations + "1", len);
printGoodSeqs(count, combinations + "2", len);
printGoodSeqs(count, combinations + "3", len);
} else if (len == combinations.length()){
//check
if (count[0] == 0){
System.out.println(combinations);
count[0]++;
} else {
return;
}
return;
} else if (count[0] >0) {
return;
} else {
if (combinations.charAt(combinations.length()-1) != '1'){
printGoodSeqs(count, combinations + "1", len);
}
if (combinations.charAt(combinations.length()-1) != '2'){
printGoodSeqs(count, combinations + "2", len);
}
if (combinations.charAt(combinations.length()-1) != '3'){
printGoodSeqs(count, combinations + "3", len);
}
}
} else return;
}
public static boolean isGoodSequence(String combinations){
//check length
int length = combinations.length()/2;
for (int i=1; i<=length; i++){
//i is designated length;
for (int j=0; j<=combinations.length() - 2*i; j++){
if (combinations.substring(j, j+i).equals(combinations.substring(j+i, j+2*i))){
return false;
}
}
}
return true;
}
}'Recursion' 카테고리의 다른 글
4-9: 웜바이러스 (0) 2018.10.24 4-8: 부등호 (0) 2018.10.24 4-6: 단지번호 붙이기 (0) 2018.10.24 4-5: Dessert (0) 2018.10.24 4-4: Division (0) 2018.10.24