首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在java中查找集合的所有可能组合

在java中查找集合的所有可能组合
EN

Stack Overflow用户
提问于 2017-04-03 00:09:42
回答 1查看 564关注 0票数 1

好的,我们基本上有这个问题要回答,但我很困惑,不知道如何使用递归来获得所有可能的组合。

编写一个public static method threadings,它接受一个int n (表示每个项链上的珠子的数量)和一组Strings (表示可用的珠子colours;您的代码不能改变这一组),并返回一组ArrayLists of Strings,表示给定颜色的n个珠子可以穿线的所有顺序。如果为n < 1,则返回一个仅包含一个空ArrayList的集。

正确行为的例子:

·threadings(0, {red,green}) = {[]}

·threadings(1, {red,green}) = {[red],[green]}

·threadings(2, {red,green}) = {[red,red],[red,green],[green,red],[green,green]}

·threadings(3, {red}) = {[red,red,red]}

提示:您可能希望threadings递归地调用自身,尽管对于任何正确的方法都有完整的标记。

代码语言:javascript
运行
复制
 public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){
    HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>();
    ArrayList<String> inresult= new ArrayList<String>();
    String[] col= new String[colours.size()];
    if (n==0){
        result.add(inresult);
        return result;
    }else{

    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-04-03 05:17:25

试试这个:

代码语言:javascript
运行
复制
public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) {
    List<String> colorsList = new ArrayList<>(colours);
    ArrayList<String> resultList = new ArrayList<>();
    HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>();
    int carry;
    int[] indices = new int[n];
    do
    {
        for(int index : indices) {
            resultList.add(colorsList.get(index));
        }
        result.add(resultList);
        resultList = new ArrayList<>();

        carry = 1;
        for(int i = indices.length - 1; i >= 0; i--)
        {
            if(carry == 0)
                break;

            indices[i] += carry;
            carry = 0;

            if(indices[i] == colorsList.size())
            {
                carry = 1;
                indices[i] = 0;
            }
        }
    }
    while(carry != 1);

    return result;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43170507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档