https://www.acmicpc.net/problem/15649
This is a typical dfs backtracking problem that I struggled a little bit. I didn't know how to backtrack but the main important bit is
1) "return"ing when you have reached the main condition (like len(tmp)==m) for time efficiency so that you break out early
2) for backtracking, main logic is after dfs(), you marked visited[i] back to False for other DFS paths to traverse and path.pop() the last element of your path for other elements in the list to be traversed.
my correct solution
n,m= map(int,input().split())
lst = [i for i in range(1,n+1)]
tmp = []
visited = [False for _ in range(n)]
def dfs(tmp):
if len(tmp)==m:
formatted_string = ' '.join(map(str, tmp))
print(formatted_string)
return
for i in range(len(lst)):
if not visited[i]:
tmp.append(lst[i])
visited[i]=True
dfs(tmp)
visited[i]=False
tmp.pop()
dfs(tmp)
They didnt use visited list but checked that visited condition via if i not in s where s is a list like my implementation.
n,m = list(map(int,input().split()))
s = []
def dfs():
if len(s)==m:
print(' '.join(map(str,s)))
return
for i in range(1,n+1):
if i not in s:
s.append(i)
dfs()
s.pop()
dfs()
Time Complexity:
lst
, and you explore all possible combinations.n
choices at the first level, n-1
choices at the second level, and so on.m
from a list of n
elements.Space Complexity:
tmp
list, visited
list, and the recursive call stack.tmp
list stores the current combination, and its maximum size can be m
, so the space complexity is O(m).visited
list stores whether an element has been visited or not, which also has a maximum size of n
, so the space complexity is O(n).m
, as you are making recursive calls for each element in the combination, so the space complexity for the call stack is O(m).n
is much larger than m
.In summary, the time complexity of your code is roughly O(n^m), and the space complexity is O(n) in most practical cases, assuming n
is significantly larger than m
.