好的,我们基本上有这个问题要回答,但我很困惑,不知道如何使用递归来获得所有可能的组合。
编写一个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递归地调用自身,尽管对于任何正确的方法都有完整的标记。
 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{
    }
}发布于 2017-04-03 05:17:25
试试这个:
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;
}https://stackoverflow.com/questions/43170507
复制相似问题