= A [, 2, 3 ] the n- = len (A) RES = [] DEF Permutation (A, Solution): # Note that this use global modification res, in order to update the results of global RES IF len (A) == 0 : res.append (Solution) return for I in Range (len (A)):
newsolution = + Solution [A [I]] new _a = A [: I] + A [I +. 1 :] Permutation (new _a, newsolution) Permutation (A, []) Print (RES) output: [[ 1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
The basic idea:
In fact, for backtracking, we need to start thinking about the reverse. Every time we choose from the original array was added to a result, when there is no element in the original array (new) (i.e. len (a) == 0, this time the result is [1,2,3]), we to give the first arrangement, the arrangement will be added to the result set, and then return to the previous step, that is, we have now [1,2], and then return to step [1], at which time was added 3, then add 2 to give [1,3,2],
And so on.