[英]find all possible combinations of a set in java
好吧所以我們基本上有這個問題要回答,但我很困惑,不知道如何使用遞歸來獲得所有可能的組合..請有人救我!
編寫一個public static method threadings
,它采用int n
(表示每條項鏈上的珠子數量)和一組Strings
(表示可用的珠子colours
;您的代碼不得更改此Set),並返回一組ArrayLists
Strings
,表示給定顏色的n個珠子可以穿線的所有順序。 如果n < 1
,則返回一個僅包含一個空的ArrayList
的Set。
正確行為的例子:
• 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{
}
}
嘗試這個:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.