-1

给定一个字符串数组

String[] values = {"A", "B", "C", "D", "E"};

和一个常数

 final String X = "X";

生成值数组可以包含 0 个或多个 X 的所有可能方式

IE

    [A, B, C, D, E]
    [A, X, X, D, E]
    [A, B, X, D, E]
    [X, X, X, X, X]

依此类推。需要快速 - 有点脑筋急转弯我无法提高效率。不像听起来那么容易。

4

1 回答 1

1

答案在 Joachim Sauer 的暗示中:

      String[] values = {"A", "B", "C", "D", "E"};
    final String ONE = "1";
    final String X = "X";
    int control=0;
    StringBuilder sb = new StringBuilder(values.length);
    String copy[];
    int count = Integer.parseInt(new String(new char[values.length]).replace("\0", ONE), 2) ;
    while (control <= count) {
        sb.delete(0, sb.length());
        sb.append(String.format("%" + values.length  + "s", Integer.toBinaryString(control++)).replace(' ', '0'));
        copy = values.clone();
        for (int x = 0; x < sb.length(); x ++) {
            if (sb.substring(x, x+1).equals(ONE)) {
                copy[x] = X;
            }
        }
       System.out.println(control + " " + Arrays.toString(copy));
       map.put(generateHashCode(copy),copy.clone());
    }


    System.out.println(map.values().size());
于 2012-09-18T18:14:55.083 回答