Java计算给定int数组的所有可能组合

标签 java arrays

我正在尝试构建一个程序,该程序将接受一个 int({1,2,3} 数组和一个长度值,并计算该数组的所有可能组合。

例如:

int[] arr= new char[] {0,1};
int[] tes  = new int[3];
possiblecomb(2, arr,tes,0);

这将输出:

 00
 10
 01
 11

但是当我尝试在 for 循环中调用 possiblecomb 时,我不断收到 Stack overflow 错误

 import java.util.Arrays;

 public class Program {

public static void main(String[] args) {

    // Create an arr to work with
    int[] test = new int[] {0,1};
     int[] tes  = new int[3];
    // Find all possible combinations of this arr in the string size of 3
    possiblecomb(3, test,tes,0);
}

public static void possiblecomb(int maxLength, int[] nums, int[] curr,int end) {

    // If the current array has reached it's maximum length
    if(end == maxLength) {
        System.out.println(Arrays.toString(curr));

    // Else add each number from the numbs to new array and process these new arrays again
    } else {
        for(int i = 0; i < nums.length; i++) {
            int[] oldCurr = curr.clone();
            curr[end]= nums[i];
            possiblecomb(maxLength,nums,curr,end++);
            curr = oldCurr.clone();
        }
    }
}

最佳答案

尝试将递归调用移到 for 之外。

您正在使用 for 来复制内容。

您的结束变量最终会增加到超过最大长度,并且您的 (==) 比较不会成为障碍。

以 num.Length = 2 和 end 为 2 为例:

您将使用 end = 3 调用您的函数一次,这将停止并在递归调用内部打印,接下来,当 i == 1 时,您的结束将为 4,并且递归调用不会中断。

如果您想避免当前代码的无限递归以便更好地调试输出,请放置中断条件

if (end>=maxLength)

关于Java计算给定int数组的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197564/

相关文章:

java - 这条语句的返回值是多少

java - 多维数组操作 - Java

c++ - 带指针的基于范围的循环

javascript - 从常规数组创建新的二维数组

javascript - 无法在函数内部编辑数组

c++ - 设置一个 2d char 空格数组

java - 从 MySQL 数据库解析未显示在 Activity 中

java - 错误 : Didn't find class android. view.menu(在路径上)

java - 服务器UDP和端口绑定(bind)

java - 未找到 com.sun.jersey.core.header.FormDataContentDisposition 类的消息正文阅读器