This question on LeetCode is the similar question I solved during a live coding interview this week. After that, I took some time to review BFS and DFS. I believe this is a good opportunity to gain a more extensive understanding of them.
BFS & DFS
They both are the algorithm that begins at the root node and then them explore each node to traverse graphs or trees basically.
Dfs for Level Order
1 2 4 5 3 6 7
Dfs for PreOrder
1 2 4 5 3 6 7
Dfs for InOrder
4 2 5 1 6 3 7
Dfs for PostOrder
4 5 2 6 7 3 1
Bfs for Level Order
1 2 3 4 5 6 7
Question
Solution
We have to traverse all possible combinations, so we can use the recursive backtracking approach to sovle this question step by step following.
First we can define a private recursive method helper that takes two arguments that one is the input array nums, and the other is a list list that represents the current permutation.
In the helper method, check if the length of list is equal to the length of nums. If so, we have generated a complete permutation and we add a copy of list to the res list. Otherwise, for each element in nums, check if it has already been included in the current permutation. If not, add it to list, recursively call helper with the updated list, and remove the last element from list before proceeding to the next iteration.
Therefore, We can call the helper method with an empty list as the starting permutation.