获取字符串的所有组合 [英] get all combinations for a string

查看:536
本文介绍了获取字符串的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JavaScript中创建一个函数,给定一个字符串将返回一个字母的所有可能组合的数组,每个字符最多使用一次,从最短的开始。例如,对于字符串ABC,它将返回:

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:

A
B
C
AB
AC
ABC

我可以像这样使用循环:

I could use loops like so:

for(i=0; i<string.length; i++) {
   //add string[i]
}
for(i=0; i<string.length; i++) {
    for(a=i; a<string.length; a++) {
            //add string[i]+string[a]
    }
}
for(i=0; i<string.length; i++) {
    for(a=i; a<string.length; a++) {
        for(b=a; b<string.length; b++) {
            //add string[i]+string[a]+string[b]
        }
    }
}

但我不知道字符串的长度,所以不会我不知道要使用多少循环。

But I don't know the length of the string, so wouldn't know how many loops to use.

任何想法?

编辑:我不是要求不应返回排列,abc和acb。数组中第一个最短也很重要。

I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.

这不是作业。这是一个解决'熄灯'型游戏的程序。

This is not homework. It's for a program to solve a 'lights-out' type game.

推荐答案

这就是我最终使用的。

var combinations = function (string)
{
    var result = [];

    var loop = function (start,depth,prefix)
    {
        for(var i=start; i<string.length; i++)
        {
            var next = prefix+string[i];
            if (depth > 0)
                loop(i+1,depth-1,next);
            else
                result.push(next);
        }
    }

    for(var i=0; i<string.length; i++)
    {
        loop(0,i,'');
    }

    return result;
}

这篇关于获取字符串的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆