728x90
해당 문제는 완전탐색문제로 해결할 수 있습니다. 각각의 숫자에 대하여 +, -, ‘ ‘ 연산을 수행해봄으로서
N이 9보다 작거나 같기 때문에 최악의 연산 횟수는 O(3^8) 입니다. 테스트 케이스 또한 10 이하 이기때문에
O(10* 3^8) 임으로 충분히 시간안에 풀 수 있습니다. 깊이우선 탐색으로 경우의 수를 모두 구한뒤 구한 결과를 0인지 아닌지에 따라서 결과를 출력 하면 됩니다.
oper = ['+', '-', ' ']
def dfs(depth, sequence):
if depth == N:
newsequence = sequence.replace(' ', '')
total = eval(newsequence)
if 0 == total:
ans.append(sequence)
return
else:
return
for op in oper:
newsequence = sequence + op + str(depth+1)
dfs(depth+1,newsequence)
T = int(input())
for i in range(T):
N = int(input())
ans = []
dfs(1, '1')
ans.sort()
for temp in ans:
print(temp)
if T-1 > i:
print()
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 1051번 : 숫자 정사각형 (0) | 2023.10.19 |
---|---|
[백준] 1182번 : 부분수열의 합 (2) | 2023.10.19 |
[백준] 1941번 : 소문난 칠공주 (2) | 2023.10.19 |
[백준] 17136번 : 색종이 붙이기 (0) | 2023.10.19 |
[백준] 1300번 : K번째 수 (0) | 2023.10.19 |