排列组合分析

输入数组和排列数:[1,2,3,4] 3          输出: [[1, 2, 3],[1, 2, 4],[13, 4],[ 2, 3, 4]]

 function combination(arr, m) {
            let res = [];
            handle([], arr, m);
            return res;
            function handle(t, a, m) {
                //t:临时数组 a:目标数组 m:组合数
                if (m === 0) {
                    res[res.length] = t;//相当于push
                    return;
                }
                for (let i = 0; i <= a.length - m; i++) {
                    //从0开始 到n-m

                    let b = t.slice();//将t拷贝给b 
                    b.push(a[i])
                    handle(b, a.slice(i + 1), m - 1);
                }
            }
        }
        console.log(combination([1,2,3,4],3));

 

posted @ 2022-04-20 17:52  这个攻城狮不太冷静  阅读(21)  评论(0编辑  收藏  举报