/** * File: permutations_i.dart * Created Time: 2023-08-10 * Author: liuyuxin (gvenusleo@gmail.com) */ /* Backtracking algorithm: Permutation I */ void backtrack( List state, List choices, List selected, List> res, ) { // When the state length equals the number of elements, record the solution if (state.length == choices.length) { res.add(List.from(state)); return; } // Traverse all choices for (int i = 0; i < choices.length; i++) { int choice = choices[i]; // Pruning: do not allow repeated selection of elements if (!selected[i]) { // Attempt: make a choice, update the state selected[i] = true; state.add(choice); // Proceed to the next round of selection backtrack(state, choices, selected, res); // Retract: undo the choice, restore to the previous state selected[i] = false; state.removeLast(); } } } /* Permutation I */ List> permutationsI(List nums) { List> res = []; backtrack([], nums, List.filled(nums.length, false), res); return res; } /* Driver Code */ void main() { List nums = [1, 2, 3]; List> res = permutationsI(nums); print("Input array nums = $nums"); print("All permutations res = $res"); }