Generating power set recursively without any loops

前端 未结 8 1271
执笔经年
执笔经年 2020-12-16 18:50

How do you write a recursive method PowerSet(String input) that prints out all possible combinations of a string that is passed to it?

For example: PowerSet(\"abc\")

8条回答
  •  青春惊慌失措
    2020-12-16 19:18

    This will also do the trick:

    var powerset = function(arr, prefix, subsets) {
      subsets = subsets || [];
      prefix = prefix || [];
      if (arr.length) {
        powerset(arr.slice(1), prefix.concat(arr[0]), subsets);
        powerset(arr.slice(1), prefix, subsets);
      } else {
        subsets.push(prefix);
      }
      return subsets;
    };
    
    powerset('abc');
    

提交回复
热议问题