I would like to better understand how we can add an item to a set as part of a function call, for example.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtrack(nums, result, [], set())
return result
def backtrack(self, nums, result, perm, visited):
if len(perm) == len(nums):
result.append(perm)
for num in nums:
if num not in visited:
visited.add(num)
self.backtrack(nums, result, perm+[num], visited)
visited.remove(num)
Looking at the for loop we can see that num is added to the array inside the backtrack function call, similarly if perm was a string then the code would look like,
backtrack(num, result, perm + str(num), visited)
This seems to suggest to me that when we want to add an item inside a function call their type must match, which is why adding num without the list cast would fail when perm is a list.
backtrack(num, result, perm + num, visited) # Fails
So then with that, is it possible to do the same for a set ? I tried
backtrack(num, result, perm + [num], visited + set(num))
backtrack(num, result, perm + str(num), visite + (num))
but both failed, seeing as an array and a set are both objects it seems strange to me that only 1 supports adding like so.
Could someone shed some light please !
Thank you