leetcode_60
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
Solutions
dfs with pruning
Note: we cannot use
swap
as we did inproblem 46
where the ordering of permutations is not required. for example:1 2 3
swapped1
with3
will be3 2 1
, the ordering of1
and2
is changed due to the swap, the permutaion order will not be guaranteed when we choose the next number. ie. 2 will be choosed before 1.Thus we use a
seen
hashset to record which number has been used in the current permutation.
Inorder to speed up the backtracking process or eliminate unnecessary backtrackings, we can pre-calculate the number of permutations will be generated in each recursive call and skip to the right recursive call where the target permutations will be created.
finding every digit
Though the intrinsic idea are the same as the first solution, the first solution follows a backtracking strategy but with efficient pruning, while this solution trys to find every digit in the final permutation in a iterative way.
use 0-based indexing to faciliate the calculation.
for example, when the group size is
2
.1-based.
5 / 2 == 4 / 2
. 5 and 4 are within the same group which is incorrect.0-based.
(5 - 1) / 2 != (4 - 1) / 2
.
Last updated
Was this helpful?