Find all combinations of two arrays

前端 未结 5 699
长情又很酷
长情又很酷 2021-02-15 17:02

I am trying to find all the combination of two arrays, but with an important variation:

Each value of the second array needs to be spread out over the val

5条回答
  •  不知归路
    2021-02-15 17:33

    I believe that your problem can be rephrased like this: generate all possible assignments of labels in left to the elements in right. This is a standard backtracking problem.

    The number of solutions is l^r (since you can assign any of the labels to each element, independently), where l is the number of elements in left and r is the number of elements in right.

    I'll provide a recursive solution, which is maybe you can rewrite in a non-recursive way, though it will not lower the complexity of the algorithm (maybe the constant). There is actually no way to lower the complexity since at some point you need to generate each solution. So do not test it for l=20 and r=20, try smaller numbers :p

    // sol keeps the labels assigned to the elements in right
    public static int[] sol = new int[r];
    
    public static void generate(int p)
    {
        for (int i=0;i

提交回复
热议问题