我试图在没有重复的情况下找到数组{"A","B","C"}
中的字符串组合,并且应该在子集中保留元素的顺序。
所需订单为[["B","C"], ["A","C"], ["A","B"], ["A","B","C"], ["A"], ["C"], ["B"]]
。我尝试使用此question中的答案编写逻辑,并发现元素的顺序不会被保留。
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:子集的顺序无关紧要,但子集内元素的顺序为。
答案 0 :(得分:3)
组合可以用数字表示 - 以二进制形式,每个位置的数字表示元素是否存在。例如。 5 = 101 - &gt; {A,C}
因此,让我们迭代组合=数字范围&lt; 0..2 ^ n-1&gt;并获得与数字对应的元素,这意味着那些索引存在于组合的二进制表示中。
public class Combins {
static String[] a = new String[] { "A", "B", "C" };
public static void main(final String[] args) {
final int maxbit = 1 << a.length;
//for each combination given by a (binary) number 'p'...
for (int p = 0; p < maxbit; p++) {
final List<String> res = new ArrayList<String>();
//evaluate if array 'a' element at index 'i' is present in combination (and include it if so)
for (int i = 0; i < a.length; i++) {
if ((1 << i & p) > 0) {
res.add(a[i]);
}
}
System.out.println(Arrays.toString(res.toArray()));
}
}
}
输出是:
[]
[A]
[B]
[A, B]
[C]
[A, C]
[B, C]
[A, B, C]