我試圖找到數組中的字符串組合{"A","B","C"}
而不重複,並且元素的順序應保留在子集中。 所需的訂單是[["B","C"], ["A","C"], ["A","B"], ["A","B","C"], ["A"], ["C"], ["B"]]
。我曾嘗試使用在此question中找到的答案編寫邏輯,並且發現元素的順序未保留。在Java中查找數組中所有字符串的組合
public static Set <JSONArray> getCombinations(int k , JSONArray properties)
{
Set <JSONArray> combinations = new LinkedHashSet <JSONArray>();
try
{
if (k == 0)
{
combinations.add(new JSONArray());
return combinations;
}
for (int i = 0 ; i < properties.length() ; i++)
{
String element = properties.getString(i);
JSONArray sublist = getSublist(properties , i + 1);
combinations.add(sublist);
Set <JSONArray> combinations2 = getCombinations(k - 1 , sublist);
for (JSONArray previous : combinations2)
{
previous.put(element);
combinations.add(previous);
}
}
}
catch (Exception e)
{
System.out.println("Exception :: " + e);
}
return combinations;
}
public static JSONArray getSublist(JSONArray list , int i) throws JSONException
{
JSONArray sublist = new JSONArray();
for (int j = i ; j < list.length() ; j++)
{
sublist.put(list.getString(j));
}
return reverseArray(sublist);
}
輸出爲:: [["B","C"], ["C","A"], ["B","A"], ["C","B","A"], ["A"], ["C"], ["B"]]
。但我需要保存命令,如[「C」,「A」]應該是[「A」,「C」]。任何想法都會有幫助。
PS:子集的順序並不重要,但子集內的元素的順序是。
爲什麼要B,C來之前A,C?或者a,b?我不知道「保持初始秩序」。或者它只是:它應該是a,c而不是c,a? – GhostCat
是的,它應該是a,b,而不是b,a。子集的順序無關緊要,但子集內的元素順序是。 – User