목록백트래킹 (6)
홍우진의 개발 일기장
문제 링크https://www.acmicpc.net/problem/15655풀이 코드n, m = map(int,input().split())arr = sorted(list(map(int,input().split())))li = []def dfs(idx, cnt): if cnt == m: print(*li) for i in range(idx, n): idx += 1 li.append(arr[i]) dfs(idx, cnt + 1) li.pop()dfs(0,0)코드 해석 백트래킹 문제다.https://woojinhong.tistory.com/295 [백준] 10974번: 모든 순열 / 파이썬문제 링크https://www.acmic..
문제 링크https://www.acmicpc.net/problem/10974 풀이 코드n = int(input())li = []def dfs(): if len(li) == n: print(*li) return for i in range(1, n + 1): if i not in li: li.append(i) dfs() li.pop()dfs()코드 해석파이썬 순열함수 itertools.permutations를 사용하는 방법이 있지만DFS 알고리즘으로 풀었다. DFS 알고리즘이란? -> https://gmlwjd9405.github.io/2018/08/14/algorithm-dfs.html [알고리즘] ..
문제 링크https://www.acmicpc.net/problem/15652풀이 코드 n,m = map(int, input().split())dap = [] def dfs(start): if len(dap) == m: print(*dap) return for i in range(start, n+1): #받은 수보다 큰 수부터 시작 dap.append(i) dfs(i) # 반복 dap.pop() #원상복구 dfs(1)코드 해석DFS를 사용하여 풀이하였다. 체감 난이도: ★★★☆☆
문제 링크https://www.acmicpc.net/problem/15650 풀이 코드n, m = map(int, input().split())s = []def f(start): if len(s) == m: print(*s) return for i in range(start, n + 1): if i not in s: s.append(i) f(i+1) s.pop() f(1)코드 해석https://woojinhong.tistory.com/151 [백준] 15649번: N과 M (1)/ 파이썬문제 링크 https://www.acmicpc.net/problem/15649 15649번: N과 ..
문제 링크https://www.acmicpc.net/problem/1182풀이 코드n, s = map(int, input().split())num = list(map(int, input().split()))cnt = 0dap = []def hap(inp): global cnt if sum(dap) == s and dap: cnt += 1 for i in range(inp, n): dap.append(num[i]) hap(i+1) dap.pop()hap(0)print(cnt)코드 해석재귀함수를 사용한다.dap이라는 빈 리스트를 만든 뒤 리스트에 숫자들을 넣는다.만약 리스트의 합이 s와 같다면 cnt + 1을 한다. n = 5, s = 0, ..

문제 링크 https://www.acmicpc.net/problem/15649 15649번: N과 M (1) 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해 www.acmicpc.net 풀이 코드 n, m = map(int, input().split()) s = [] def f(): if len(s) == m: print(' '.join(map(str, s))) return for i in range(1, n + 1): if i in s: continue s.append(i) f() s.pop() f() 코드 해석 DPS를 기반으로 풀이한다. 수열을 저장하기 위한 리..