nunnly / everycode

Javascript 每日一练
116 stars 26 forks source link

2014年12月15日 D5 #26

Open nunnly opened 9 years ago

nunnly commented 9 years ago

根据传入的数组(假设里面都是整形元素),返回这个数组的所有子集

PS :

/*
 * param Array
 * return Array
 */
function power(){

}
power([1,2,3]);
// => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
XadillaX commented 9 years ago
function power(arr) {
    return arr.sort(function(a, b) { return a - b; }).reduce(function(res, _cur) {
        return res.reduce(function(res, cur) {
            return res.push(JSON.parse(cur.substr(0, cur.length - 1) + "," + JSON.stringify(_cur) + "]")), res;
        }, [[ _cur ]]).map(function(v) { return JSON.stringify(v); }).reduce(function(res, cur) {
            return res.indexOf(cur) === -1 ? (res.push(cur), res) : res;
        }, res);
    }, []).reduce(function(res, v) { return res.push(JSON.parse(v)), res; }, [[]]);
}

以及了。

function power(a){return a.sort(function(a,b){return a-b}).reduce(function(a,b){return a.reduce(function(a,c){return a.push(JSON.parse(c.substr(0,c.length-1)+","+JSON.stringify(b)+"]")),a},[[b]]).map(function(a){return JSON.stringify(a)}).reduce(function(a,b){return-1===a.indexOf(b)?(a.push(b),a):a},a)},[]).reduce(function(a,b){return a.push(JSON.parse(b)),a},[[]])}
businiaowa commented 9 years ago
function power(arr){    
    function getSubArray(arr) {
        if(arr.length === 0) return arr;
        var first = arr.shift(),
            rel = getSubArray(arr),
            i, len = rel.length;

        rel.push([first]);
        for(i = 0; i<len; i++) {
            rel.push(rel[i].concat(first));
        }                               
        return rel;
    }
    var rel = getSubArray(arr);
    rel.push([]);

    return rel;
}
qingo commented 9 years ago
//无数字限制,不去重,就是组合所有子集,就是这么任性。
function power(arr) {
  if (arr.length === 1) {
    return [[], arr]
  } else {
    var last = arr.pop(),
        prev = power(arr),
        len = prev.length,
        i, v,
        rst = [].concat(prev);
    for (i = 0; i < len; i++) {
      v = prev[i];
      rst.push(v.concat(last));
    }
    return rst;
  }
}
teabyii commented 9 years ago
function power(arr){
  var re = [[]];
  arr.forEach(function (n, index) {
    if (arr.indexOf(n) !== index) {
      return ;
    }
    re.forEach(function (m) {
      re.push(m.concat(n));
    });
  });
  return re;
}

console.log(power([1,2,3]));
console.log(power([1,2,2,3]));
console.log(power([1,3]));
console.log(power([1,2,3,2,4]));

下班前来一发,身体健康

witoad commented 9 years ago

var a=[1,2,3,4];

function power(a){ var i=0; var result=[]; var re=[]; function pu(c,d){ var f=d.slice(); c.push(f); } function foo(b,j){ if(j>3) pu(re,result); else { result.push(b[j]); foo(b,j+1); result.pop(b[j]); foo(b,j+1); } } foo(a,i); return re } 严蔚敏奶奶那学的回溯法