S
give all the valid unique Permutations possible. S
might have duplicate characters.Examples:
Input: [1,2,3]
Output: [1,2,3], [2,1,3], [3
This question has choices and decisions involved, therefore this should be a recursion problem.
input
string is null
, insert the output
string to result
arrayfunction permutations(input, output="", result=[]) {
if(!input.length) {
result.push(output);
}
}
Store current input
in a temorary tempInput
Loop through the characters of the input
string
For every character,
input
stringoutput
stringpermutations(input, output, result)
input
to the original state by assigning input = tempInput
Return result
function permutations(input, output="", result=[]) {
if(!input.length) {
result.push(output);
}
for(let i=0; i<input.length; i++) {
let char = input[i]
if(!output.includes(char)) {
let tempInput = input
input = input.substring(0,i) + input.substring(i+1)
output = output + char
permutations(input, output, result)
input = tempInput
}
}
return result
}
//Usage
permutations("abc")
Previous
Next