/** * File: permutations_ii.dart * Created Time: 2023-08-10 * Author: liuyuxin (gvenusleo@gmail.com) */ /* Backtracking algorithm: Permutation II */ 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 Set duplicated = {}; for (int i = 0; i < choices.length; i++) { int choice = choices[i]; // Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements if (!selected[i] && !duplicated.contains(choice)) { // Attempt: make a choice, update the state duplicated.add(choice); // Record selected element values 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 II */ List> permutationsII(List nums) { List> res = []; backtrack([], nums, List.filled(nums.length, false), res); return res; } /* Driver Code */ void main() { List nums = [1, 2, 2]; List> res = permutationsII(nums); print("Input array nums = $nums"); print("All permutations res = $res"); }