【发布时间】:2017-08-27 11:39:54
【问题描述】:
好的,所以我们基本上有这个问题要回答,但我很困惑,不知道如何使用递归来获得所有可能的组合。请有人救救我!
写一个public static method threadings,它需要一个int n(代表每条项链上的珠子数量)和一组Strings(代表可用的珠子colours;你的代码不能改变这个Set),并返回ArrayLists 的Strings 的集合,表示可以穿入给定颜色的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