Golang Leetcode 823. Binary Trees With Factors.go

思路

dp
从最小的数开始
dp[c] = sum{dp[a]dp[b]};c=ab;a,b,c in A
ans = sum(dp[c])

code

func numFactoredBinaryTrees(A []int) int {
	mod := 1000000007
	sort.Ints(A)
	dp := make(map[int]int)
	for i := 0; i < len(A); i++ {
		dp[A[i]] = 1
		for j := 0; j < i; j++ {
			if A[i]%A[j] == 0 {
				if _, ok := dp[A[i]/A[j]]; ok {
					dp[A[i]] += (dp[A[j]] * dp[A[i]/A[j]]) % mod
				}
			}
		}
	}
	ans := 0
	for _, v := range dp {
		ans += v
	}
	return ans % mod
}

更多内容请移步我的repo:https://github.com/anakin/golang-leetcode

你可能感兴趣的:(leetcode-golang,golang,leetcode,算法)