【发布时间】:2017-11-23 23:08:47
【问题描述】:
我有一个程序,给定一个数组,返回其值的所有可能组合(排列?)。我递归地这样做。它计算得很好,但是,我想做的是,不是每次迭代都打印结果数组,而是想将它附加到我之前声明的数组列表中。
public static final int NUMBER_OF_CELLS = 3;
public static final int NUMBER_OF_ATTRIBUTES = 3;
// I want all possible combinations all elements 0, 1 and 2, taken 3 at a time
private ArrayList<State> states= new ArrayList<State>();
public void createAllPossibleStates() {
State state = new State(NUMBER_OF_CELLS);
setValues(0, state);
System.out.println(states); // This gives me a wrong ouput and I don't know why
}
public void setValues(int cell, State state) {
if(cell == NUMBER_OF_CELLS) {
// System.out.println(state.toString()); // Instead of this
states.add(state); // I want this. Append the array to an array list
}
}
else {
for(int i = 0; i < NUMBER_OF_ATTRIBUTES; i++) {
state.values[cell] = i;
setValues(cell + 1, state);
}
}
}
但是最终的 Array List 包含所有可能的状态的结果是错误的。而不是这个:
[[0, 0, 0],[0, 0, 1],[0, 0, 2],[0, 1, 0],[0, 1, 1],[0, 1, 2],[0, 2, 0],[0, 2, 1],[0, 2, 2],[1, 0, 0],[1, 0, 1],[1, 0, 2],[1, 1, 0],[1, 1, 1],[1, 1, 2],[1, 2, 0],[1, 2, 1],[1, 2, 2],[2, 0, 0],[2, 0, 1],[2, 0, 2],[2, 1, 0],[2, 1, 1],[2, 1, 2],[2, 2, 0],[2, 2, 1],[2, 2, 2]]
我明白了:
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
我不知道为什么会这样。也许递归事实导致附加操作以错误的方式工作?
【问题讨论】:
标签: java arrays recursion combinations permutation