递归:
public static void main(String[] args){
int[] array = {1, 2, 3, 4, 5};
for (int i = 1; i <= array.length; i++) {
findChildOrder(0, 1, array, new int[i]);
}
}
public static void findChildOrder(int start, int currentLength, int[] array, int[] childOrder) {
for (int i = start; i < array.length; i++) {
childOrder[currentLength - 1] = array[i];
if (currentLength < childOrder.length) {
findChildOrder(i + 1, currentLength + 1, array, childOrder);
} else {
doSomething(childOrder);
}
}
}
非递归:
stackLength表示子序列长度,stacks存放子序列每个元素在array里对应的下标
public static void main(String[] args){
int[] array = {1, 2, 3, 4, 5};
findChildOrderNonRecursive(array);
}
public static void findChildOrderNonRecursive(int[] array) {
int[] stacks = new int[array.length];
for (int stackLength = 0; stackLength < array.length; stackLength++) {
for (int i = 0; i <= stackLength; i++) {
stacks[i] = i;
}
while (stacks[0] < array.length - stackLength) {
doSomething(stacks, array, stackLength);
if (++stacks[stackLength] >= array.length) {
for (int j = stackLength - 1; j >= 0; j--) {
if (++stacks[j] < array.length - (stackLength - j)) {
int firstValue = stacks[j];
for (int k = j + 1; k <= stackLength; k++) {
stacks[k] = ++firstValue;
}
break;
}
}
}
}
}
}
本文介绍了使用递归和非递归方法实现的一种算法。递归版本通过不断调用自身来生成不同长度的子序列,而非递归版本则利用栈结构进行迭代处理。两种方法都用于从给定数组中生成所有可能的子序列,并通过回调函数处理每个子序列。
512

被折叠的 条评论
为什么被折叠?



