Skip to main content
Code Review

Return to Revisions

3 of 3
replaced http://stackoverflow.com/ with https://stackoverflow.com/

A recursive solution, originally seen here, but modified to fit your requirements (and look a little more JavaScript-y):

function combinations(str) {
 var fn = function(active, rest, a) {
 if (!active && !rest)
 return;
 if (!rest) {
 a.push(active);
 } else {
 fn(active + rest[0], rest.slice(1), a);
 fn(active, rest.slice(1), a);
 }
 return a;
 }
 return fn("", str, []);
}

Test:

combinations("abcd")

Output:

["abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d"]

Regarding the name: Don't name it permutations; a permutation is an arrangement of all the original elements (of which there should be n! total). In other words, it already has a precise meaning; don't unnecessarily overload it. Why not simply name it combinations?

Wayne
  • 1k
  • 8
  • 10
default

AltStyle によって変換されたページ (->オリジナル) /