Given an array, how to generate all combinations of subset size k?

后端 未结 3 895
面向向阳花
面向向阳花 2021-01-06 15:16

So given input = [1, 2, 3] and k=2 this would return:

1 2
1 3
2 1
2 3
3 1
3 2

This is the closest to what I am lo

3条回答
  •  离开以前
    2021-01-06 15:29

    Instead of combinations, try permutations.

    Try generating permutations, then resizing the array.

    Here's it implemented, modified from here

    var permArr = [],
      usedChars = [];
    
    function permute(input, k) {
      var i, ch;
      for (i = 0; i < input.length; i++) {
        ch = input.splice(i, 1)[0];
        usedChars.push(ch);
        if (input.length == 0) {
          var toadd = usedChars.slice(0,k);
          if(!permArr.includes(toadd)) permArr.push(toadd); // resizing the returned array to size k
        }
        permute(input, k);
        input.splice(i, 0, ch);
        usedChars.pop();
      }
      return permArr
    };
    console.log(JSON.stringify(permute([1, 2, 3], 2)));

提交回复
热议问题