Binary Trees With Factors LeetCode solution in C++
1class Solution {2public:3const int mod = 1e9 + 7;4int numFactoredBinaryTrees(vector<int> &arr) {5sort(arr.begin(), arr.end());6int n = arr.size();78vector<int> dp(n, 1);910for (int i = 1; i < n; i++) {11int l = 0, r = i - 1;12while (l <= r) {13if (arr[l] * 1LL * arr[r] == arr[i] * 1LL) {14if (l != r)15dp[i] = (dp[i] + (dp[l] * 1LL * dp[r] % mod * 2LL % mod)) % mod;16else17dp[i] = (dp[i] + (dp[l] * 1LL * dp[r] % mod)) % mod;18l++, r--;19} else if (arr[l] * 1LL * arr[r] > arr[i] * 1LL)20r--;21else22l++;23}24}2526int ans = 0;27for (auto i : dp) ans = (ans + i) % mod;28return ans;29}30};