【问题标题】:find all possible combinations of a set in java在java中找到集合的所有可能组合
【发布时间】:2017-08-27 11:39:54
【问题描述】:

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

写一个public static method threadings,它需要一个int n(代表每条项链上的珠子数量)和一组Strings(代表可用的珠子colours;你的代码不能改变这个Set),并返回ArrayListsStrings 的集合,表示可以穿入给定颜色的n 个珠子的所有顺序。如果n < 1,则返回一个只包含一个空的Set,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 递归调用自身,尽管 任何正确的方法都可以获得满分。

这是我到现在为止写的:

 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{

    }
}

【问题讨论】:

  • 或者在stackoverflow上:stackoverflow.com/a/42911720/5057029
  • 参考this问题。使用集合将是相似的
  • 是递归的问题吗?自从我是递归初学者以来,我一直这样想:在编码threadings(n, colours) 时,假设您已经有一种方法可以为您提供n - 1 珠子和相同颜色的可能线程。你还没有,想象一下你有,你很快就会有,我保证。那么编码方法就不那么难了。

标签: java arrays list combinations


【解决方案1】:

试试这个:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多