Files
hello-algo/en/codes/javascript/chapter_backtracking/permutations_ii.js
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

45 lines
1.4 KiB
JavaScript

/**
* File: permutations_ii.js
* Created Time: 2023-05-13
* Author: Justin (xiefahit@gmail.com)
*/
/* Backtracking: permutations II */
function backtrack(state, choices, selected, res) {
// Record a solution when the state length equals the number of elements
if (state.length === choices.length) {
res.push([...state]);
return;
}
// Iterate over all choices
const duplicated = new Set();
choices.forEach((choice, i) => {
// Prune: do not reuse an element or choose the same value again at this depth
if (!selected[i] && !duplicated.has(choice)) {
// Try: make a choice and update the state
duplicated.add(choice); // Record the chosen value
selected[i] = true;
state.push(choice);
// Proceed to the next choice
backtrack(state, choices, selected, res);
// Backtrack: undo the choice and restore the previous state
selected[i] = false;
state.pop();
}
});
}
/* Permutations II */
function permutationsII(nums) {
const res = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
// Driver code
const nums = [1, 2, 2];
const res = permutationsII(nums);
console.log(`Input array nums = ${JSON.stringify(nums)}`);
console.log(`All permutations res = ${JSON.stringify(res)}`);