给出一个数字数组<Number>[], 如[1, 2, 3], 如何打印出全部的排列A33(这里打不出来上下标,见谅)。 即: 打印出[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]。面试
咱们先来看看排列组合在数学上的概念:数组
排列指的是从n个不一样元素中,任取m(m≤n,m与n均为天然数,下同)个不一样的元素按照必定的顺序排成一列,叫作从n个不一样元素中取出m个元素的一个排列。缓存
组合指的是从n个不一样元素中,任取m(m≤n)个元素并成一组,叫作从n个不一样元素中取出m个元素的一个组合。oop
贴下个人回答:优化
function permutationAndCombination(source = [], selectedLimit, isPermutation = true) {
if (!Array.isArray(source)) return source
// remove duplicated item
source = [...new Set(source)]
selectedLimit = selectedLimit || source.length
const result = []
const sourceLen = source.length
selectedLimit = selectedLimit > sourceLen ? sourceLen : selectedLimit
const innerLoop = (prefix = [], done = [], index = 0) => {
const prefixLen = prefix.length
for (let i = isPermutation ? 0 : index; i < sourceLen; i++) {
if (prefixLen > selectedLimit - 1) break
// Optimization: Continue to next cycle if current item has be already used for 'prefix'.
if (done.includes(i)) continue
const item = source[i]
const newItem = [...prefix, item]
if (prefixLen === selectedLimit - 1) {
result.push(newItem)
}
if (prefixLen < selectedLimit - 1) {
innerLoop(newItem, [...done, i], index++)
}
}
}
if (source.length) {
// there is only one case if we want to select all items from source by combination.
if (!isPermutation && selectedLimit === sourceLen) {
return source
}
innerLoop()
}
return result
}
复制代码
permutationAndCombination([1, 2, 3])
复制代码
结果以下ui
permutationAndCombination([1, 2, 3], 2)
复制代码
结果以下spa
permutationAndCombination([1, 2, 3], 1)
复制代码
结果以下code
// remove duplicated item
source = [...new Set(source)]
复制代码
permutationAndCombination([1, 2, 3, 3])
复制代码
结果以下cdn
若是咱们在排列的时候不想忽略重复的,就须要作一个缓存,已经出现的就不须要再次操做了。blog
// there is only one case if we want to select all items from source by combination.
if (!isPermutation && selectedLimit === sourceLength) {
return source
}
复制代码
permutationAndCombination([1, 2, 3], 3, false)
复制代码
结果以下
permutationAndCombination([1, 2, 3], 2, false)
复制代码
结果以下
permutationAndCombination([1, 2, 3], 1, false)
复制代码
结果以下