Divide Array to 2 sub arrays and check if the multiplication are equal

时光怂恿深爱的人放手 提交于 2019-12-04 06:40:35

Your solution gives false positives. For example, the array {2,8} cannot be divided into two sub-arrays of equal product, but you'll return true, since the square root of 2*8 is 4.

When you try to solve such a recursion you should try to think what happens if you reduce the size of the input by 1.

Suppose a given array arr has a valid split (into two sub-groups having equal product). This means that if you remove the first element a[0], you must be able to split the rest of the array into two sub-groups such that p1 == p2 * a[0] or p1 == p2 / a[0], where p1 is the product of the elements of the first group and p2 is the product of the elements of the second group.

This suggests that the recursive method should check whether for a given tail of the input array (i.e. arr[from]...arr[arr.length-1] for some from >= 0), there exists a split into two groups such that the product of the first group divided by the product of the second group (or vice versa) equals a given factor:

public static boolean canSplit(int[] arr, int from, double factor)
{
    if (from == arr.length - 1) {
        return arr[from] == factor;
    }
    return canSplit(arr, from + 1, factor * arr[from]) || canSplit(arr, from + 1, factor / arr[from]);
}

The initial call will be:

public static boolean canSplit(int[] arr)
{
    if (arr.length < 2) {
        return false;
    } else {
        return canSplit(arr, 0, 1); // the second parameter is 0, since the first recursive call
                                    // applies to the whole array
                                    // the third parameter is 1, since we want to check if there 
                                    // are two groups such that the product of the first divided
                                    // by the product of the second is 1 (i.e. the two products
                                    // are equal)
    }
}

Tests:

System.out.println (canSplit(new int[]{2,15,3,4,2,5}));
System.out.println (canSplit(new int[]{2,4,6,2,3,4}));
System.out.println (canSplit(new int[]{2,2,4}));
System.out.println (canSplit(new int[]{2,8}));

Output:

true
false
true
false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!