[백준] 1759 (Swift, Python) - 백트래킹

brick·2023년 3월 21일
0

코테

목록 보기
50/53
/*
시간 복잡도: O(C^L)
공간 복잡도: O(L)
*/
let LC: [Int] = readLine()!
    .split(separator: " ")
    .map { Int($0)! }

let L: Int = LC[0]
let C: Int = LC[1]
var characters: [String] = readLine()!
    .split(separator: " ")
    .map { String($0) }
    .sorted()    


let vowels: [String] = ["a", "e", "i", "o", "u"]
var answer: [String] = []

func backTracking(index: Int, count: Int) { 

    if index == L {
        var countOfVowels: Int = 0
        var countOfConsonant: Int = 0

        for s: String in answer {                           
            if vowels.contains(s) { countOfVowels += 1 }    
            else { countOfConsonant += 1 }
        }

        if countOfVowels >= 1 && countOfConsonant >= 2 {    
            print(answer.joined())
        }
        return 
    }

    for i: Int in count..<C {                               
        answer.append(characters[i])
        backTracking(index: index+1, count: i+1)
        answer.removeLast()
    }
}

backTracking(index: 0, count: 0)
import sys
input = sys.stdin.readline


def back_tracking(cnt, idx):

    if cnt == l:
        vo, co = 0, 0

        for i in range(l):
            if answer[i] in vowels:
                vo += 1
            else:
                co += 1
        if vo >= 1 and co >= 2:
            print("".join(answer))
        return

    for i in range(idx, c):
        answer.append(words[i])
        back_tracking(cnt+1, i+1)
        answer.pop()


l, c = map(int, input().split())
words = sorted(list(map(str, input().split())))
vowels = ['a', 'e', 'i', 'o', 'u']
answer = []

back_tracking(0, 0)

0개의 댓글