Skip to content

Commit 69c27a0

Browse files
committed
2025-01-02 v. 7.6.2: updated "823. Binary Trees With Factors"
1 parent 921a5f3 commit 69c27a0

File tree

4 files changed

+53
-1
lines changed

4 files changed

+53
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,7 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
624624
| 797. All Paths From Source to Target | [Link](https://leetcode.com/problems/all-paths-from-source-to-target/) | [Link](./lib/medium/797_all_paths_from_source_to_target.rb) | [Link](./test/medium/test_797_all_paths_from_source_to_target.rb) |
625625
| 814. Binary Tree Pruning | [Link](https://leetcode.com/problems/binary-tree-pruning/) | [Link](./lib/medium/814_binary_tree_pruning.rb) | [Link](./test/medium/test_814_binary_tree_pruning.rb) |
626626
| 817. Linked List Components | [Link](https://leetcode.com/problems/linked-list-components/) | [Link](./lib/medium/817_linked_list_components.rb) | [Link](./test/medium/test_817_linked_list_components.rb) |
627+
| 823. Binary Trees With Factors | [Link](https://leetcode.com/problems/binary-trees-with-factors/) | [Link](./lib/medium/823_binary_trees_with_factors.rb) | [Link](./test/medium/test_823_binary_trees_with_factors.rb) |
627628

628629
### Hard
629630

leetcode-ruby.gemspec

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '7.6.1'
8+
s.version = '7.6.2'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/binary-trees-with-factors/
4+
# @param {Integer[]} arr
5+
# @return {Integer}
6+
def num_factored_binary_trees(arr)
7+
mod = 1_000_000_007
8+
arr.sort!
9+
dp = ::Array.new(arr.size, 1)
10+
index = {}
11+
arr.each_with_index { |val, i| index[val] = i }
12+
(0...arr.size).each do |i|
13+
(0...i).each do |j|
14+
next unless (arr[i] % arr[j]).zero?
15+
16+
r = arr[i] / arr[j]
17+
18+
dp[i] = (dp[i] + dp[j] * dp[index[r]]) % mod if index.key?(r)
19+
end
20+
end
21+
22+
result = 0
23+
dp.each { |val| result = (result + val) % mod }
24+
25+
result
26+
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/823_binary_trees_with_factors'
5+
require 'minitest/autorun'
6+
7+
class BinaryTreesWithFactorsTest < ::Minitest::Test
8+
def test_default_one
9+
assert_equal(
10+
3,
11+
num_factored_binary_trees(
12+
[2, 4]
13+
)
14+
)
15+
end
16+
17+
def test_default_two
18+
assert_equal(
19+
7,
20+
num_factored_binary_trees(
21+
[2, 4, 5, 10]
22+
)
23+
)
24+
end
25+
end

0 commit comments

Comments
 (0)