All possible combinations of an array

前端 未结 7 622
甜味超标
甜味超标 2020-11-30 05:51

I have an string array

{\"ted\", \"williams\", \"golden\", \"voice\", \"radio\"}

and I want all possible combinations of these keywords in

7条回答
  •  -上瘾入骨i
    2020-11-30 06:31

    My optimized solution is based on the solution provided by Matthew McPeak. This version avoids unnecessary array copies.

    public static  T[][] combinations(T[] a) {
    
        int len = a.length;
        if (len > 31)
            throw new IllegalArgumentException();
    
        int numCombinations = (1 << len) - 1;
    
        @SuppressWarnings("unchecked")
        T[][] combinations = (T[][]) java.lang.reflect.Array.newInstance(a.getClass(), numCombinations);
    
        // Start i at 1, so that we do not include the empty set in the results
        for (int i = 1; i <= numCombinations; i++) {
    
            @SuppressWarnings("unchecked")
            T[] combination = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(),
                    Integer.bitCount(i));
    
            for (int j = 0, ofs = 0; j < len; j++)
                if ((i & (1 << j)) > 0)
                    combination[ofs++] = a[j];
    
            combinations[i - 1] = combination;
        }
    
        return combinations;
    }
    

提交回复
热议问题