猿问

一道javascript算法面试题

说是javascrip算面面试题有点片面了,任何语言都可以哈,题面是这样的:
有一个数组,如果有3个值:[3,2,6]。交叉组合后返回:3-2,3-6,2-6,3-2-6

有一个数组,如果有4个值:[3,2,6,9]。交叉组合后返回:3-2,3-6,3-9,2-6,2-9,6-9,3-2-6,3-2-9,2-6-9,3-2-6-9

5个值,6个值以此类推

求各大神指教如何实现


暮色呼如
浏览 963回答 3
3回答

慕仙森

function combine (arr, step = 1) {&nbsp; const result = []&nbsp; for (let i = 0; i < arr.length; i++) {&nbsp; &nbsp; const head = arr.slice(i, i + step).join('-') + '-'&nbsp;&nbsp; &nbsp; for (let j = i + step; j < arr.length; j++) {&nbsp; &nbsp; &nbsp; result.push(head + arr[j])&nbsp; &nbsp; }&nbsp; }&nbsp; return step < arr.length ? result.concat(combine(arr, step + 1)) : result}console.log(combine([3, 2, 6, 9]))

杨魅力

let nums = [3, 2, 6, 9];let cut = (arr, index) => arr.slice(index + 1, arr.length - index)let map = (prefix, suffix) => {&nbsp; &nbsp; suffix.forEach((item, index) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(`${prefix}-${item}`);&nbsp; &nbsp; &nbsp; &nbsp; map(`${prefix}-${item}`, cut(suffix, index))&nbsp; &nbsp; })}nums.forEach((num, index) => map(num, nums.slice(index + 1, nums.length)))

眼眸繁星

var arr = [3,2,6,9]// 以3,2,6,9为例子function fun (arr) {&nbsp; &nbsp; // copy&nbsp; &nbsp; var newArr = arr.slice(arr)&nbsp; &nbsp; // 结果&nbsp; &nbsp; var result = []&nbsp; &nbsp; // 先获取3开头所有,删除3,获取2开头所有,删除2......&nbsp; &nbsp; while(newArr.length) {&nbsp; &nbsp; &nbsp; &nbsp; var index = 0&nbsp; &nbsp; &nbsp; &nbsp; while(index++ < newArr.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 复制&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var temp = newArr.slice()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 数组拆分为取固定前缀(3、3-2、3-2-6)与剩余变化值[2,6,9]/[6,9]/[9]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var preArr = temp.splice(0, index)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 拼接前缀&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var pre = preArr.join('-')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp.forEach(item => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 遍历拼接剩余值&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push(pre + '-' + item) &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // 删除第一个&nbsp; &nbsp; &nbsp; &nbsp; newArr.shift()&nbsp; &nbsp; }&nbsp; &nbsp; return result}
随时随地看视频慕课网APP
我要回答