package leetcode;

/**
 * https://leetcode.com/problems/binary-trees-with-factors/
 */
public class Problem823 {
    public int numFactoredBinaryTrees(int[] A) {
        boolean[] set = new boolean[1001];;
        for (int a : A) {
            set[a] = true;;
        }
        int answer = 0;
        for (int i = 0; i < set.length; i++) {
            if (!set[i]) {
                continue;
            }
            answer += numFactoredBinaryTrees(set, i);
        }
        return answer;
    }

    private static int numFactoredBinaryTrees(boolean[] set, int root) {
        int count = 1;
        set[root] = false;;
        for (int i = 0; i < set.length; i++) {
            if (!set[i]) {
                continue;
            }
            if (root % i == 0) {
                int j = root / i;
                if (set[j]) {
                    set[i] = false;
                    count += numFactoredBinaryTrees(set, i);
                    set[i] = true;

                    set[j] = false;
                    count += numFactoredBinaryTrees(set, j);
                    set[j] = true;
                }
            }
        }
        set[root] = true;
        return count;
    }

    public static void main(String[] args) {
        Problem823 prob = new Problem823();
        System.out.println(prob.numFactoredBinaryTrees(new int[]{2, 4})); // 3
        System.out.println(prob.numFactoredBinaryTrees(new int[]{2, 4, 5, 10})); // 7
    }
}

@@ -445,32 +445,36 @@
 aryTrees(set, i)
+ + 1
 ;%0A        %7D%0A    
@@ -592,17 +592,17 @@
 count = 
-1
+0
 ;%0A      
@@ -830,24 +830,54 @@
  (set%5Bj%5D) %7B%0A
+                    count++;%0A%0A
             

Update problem 823