diff --git a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md index efa39b26b9614..dea25e375b8c0 100644 --- a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md +++ b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md @@ -55,7 +55,11 @@ And we have 0 OR 1 OR 2 OR 3 OR 4 OR 5 OR 6 = 7, so we return 7. -### Solution 1 +### Solution 1: Bit Manipulation + +We first use an array $cnt$ to count the number of 1s in each bit position. Then, from the lowest bit to the highest bit, if the number of 1s in that bit position is greater than 0, we add the value represented by that bit to the answer. Then, we check if there can be a carry-over, and if so, we add it to the next bit. + +The time complexity is $O(n \times \log M)$, where $n$ is the length of the array and $M$ is the maximum value in the array. diff --git a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md index 7b3ea9be249e8..3b8481f2934df 100644 --- a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md +++ b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md @@ -65,7 +65,11 @@ tags: -### Solution 1 +### Solution 1: Brute Force Simulation + +According to the problem statement, we can perform a process of prime factorization, i.e., continuously decompose a number into its prime factors until it can no longer be decomposed. During the process, add the prime factors each time they are decomposed, and perform this recursively or iteratively. + +The time complexity is $O(\sqrt{n})$. diff --git a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md index 62154bcd75034..2282f58338338 100644 --- a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md +++ b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md @@ -69,7 +69,19 @@ Every node in the resulting graph is connected to an even number of edges. -### Solution 1 +### Solution 1: Case Analysis + +We first build the graph $g$ using `edges`, and then find all nodes with odd degrees, denoted as $vs$. + +If the length of $vs$ is $0$, it means all nodes in the graph $g$ have even degrees, so we return `true`. + +If the length of $vs$ is $2$, it means there are two nodes with odd degrees in the graph $g$. If we can directly connect these two nodes with an edge, making all nodes in the graph $g$ have even degrees, we return `true`. Otherwise, if we can find a third node $c$ such that we can connect $a$ and $c$, and $b$ and $c$, making all nodes in the graph $g$ have even degrees, we return `true`. Otherwise, we return `false`. + +If the length of $vs$ is $4$, we enumerate all possible pairs and check if any combination meets the conditions. If so, we return `true`; otherwise, we return `false`. + +In other cases, we return `false`. + +The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the number of nodes and edges, respectively. diff --git a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md index 1fc448893b164..5f774b15838de 100644 --- a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md +++ b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md @@ -84,7 +84,13 @@ tags: -### Solution 1 +### Solution 1: Finding the Lowest Common Ancestor + +For each query, we find the lowest common ancestor of the two nodes $a$ and $b$, and record the number of steps taken upwards. The answer to the query is the number of steps plus one. + +To find the lowest common ancestor, if $a > b$, we move $a$ to its parent node; if $a < b$, we move $b$ to its parent node. We accumulate the number of steps until $a = b$. + +The time complexity is $O(n \times m)$, where $m$ is the length of the `queries` array. diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md index 4a82f40d88255..cf0d2e7252b41 100644 --- a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md +++ b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md @@ -221,41 +221,4 @@ impl Solution { - - -### 方法二 - - - -#### Rust - -```rust -impl Solution { - pub fn capture_forts(forts: Vec) -> i32 { - let mut ans = 0; - let mut i = 0; - - while let Some((idx, &value)) = forts.iter().enumerate().skip(i).find(|&(_, &x)| x != 0) { - if let Some((jdx, _)) = forts - .iter() - .enumerate() - .skip(idx + 1) - .find(|&(_, &x)| x != 0) - { - if value + forts[jdx] == 0 { - ans = ans.max(jdx - idx - 1); - } - } - i = idx + 1; - } - - ans as i32 - } -} -``` - - - - - diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md index 1ba3777a86b4d..4fa8a2942617d 100644 --- a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md +++ b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md @@ -72,7 +72,11 @@ Since 4 is the maximum number of enemy forts that can be captured, we return 4. -### Solution 1 +### Solution 1: Two Pointers + +We use a pointer $i$ to traverse the array $forts$, and a pointer $j$ to start traversing from the next position of $i$ until it encounters the first non-zero position, i.e., $forts[j] \neq 0$. If $forts[i] + forts[j] = 0$, then we can move the army between $i$ and $j$, destroying $j - i - 1$ enemy forts. We use the variable $ans$ to record the maximum number of enemy forts that can be destroyed. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the array `forts`. @@ -217,41 +221,4 @@ impl Solution { - - -### Solution 2 - - - -#### Rust - -```rust -impl Solution { - pub fn capture_forts(forts: Vec) -> i32 { - let mut ans = 0; - let mut i = 0; - - while let Some((idx, &value)) = forts.iter().enumerate().skip(i).find(|&(_, &x)| x != 0) { - if let Some((jdx, _)) = forts - .iter() - .enumerate() - .skip(idx + 1) - .find(|&(_, &x)| x != 0) - { - if value + forts[jdx] == 0 { - ans = ans.max(jdx - idx - 1); - } - } - i = idx + 1; - } - - ans as i32 - } -} -``` - - - - - diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs deleted file mode 100644 index 14ba6814a7de0..0000000000000 --- a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution2.rs +++ /dev/null @@ -1,22 +0,0 @@ -impl Solution { - pub fn capture_forts(forts: Vec) -> i32 { - let mut ans = 0; - let mut i = 0; - - while let Some((idx, &value)) = forts.iter().enumerate().skip(i).find(|&(_, &x)| x != 0) { - if let Some((jdx, _)) = forts - .iter() - .enumerate() - .skip(idx + 1) - .find(|&(_, &x)| x != 0) - { - if value + forts[jdx] == 0 { - ans = ans.max(jdx - idx - 1); - } - } - i = idx + 1; - } - - ans as i32 - } -} diff --git a/solution/2500-2599/2514.Count Anagrams/README.md b/solution/2500-2599/2514.Count Anagrams/README.md index 1bfa4d98d5cb4..d6990294eca55 100644 --- a/solution/2500-2599/2514.Count Anagrams/README.md +++ b/solution/2500-2599/2514.Count Anagrams/README.md @@ -70,23 +70,17 @@ tags: #### Python3 ```python -mod = 10**9 + 7 -f = [1] -for i in range(1, 10**5 + 1): - f.append(f[-1] * i % mod) - - class Solution: def countAnagrams(self, s: str) -> int: - ans = 1 + mod = 10**9 + 7 + ans = mul = 1 for w in s.split(): - cnt = Counter(w) - ans *= f[len(w)] - ans %= mod - for v in cnt.values(): - ans *= pow(f[v], -1, mod) - ans %= mod - return ans + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod ``` #### Java @@ -190,30 +184,4 @@ func pow(x, n int) int { - - -### 方法二 - - - -#### Python3 - -```python -class Solution: - def countAnagrams(self, s: str) -> int: - mod = 10**9 + 7 - ans = mul = 1 - for w in s.split(): - cnt = Counter() - for i, c in enumerate(w, 1): - cnt[c] += 1 - mul = mul * cnt[c] % mod - ans = ans * i % mod - return ans * pow(mul, -1, mod) % mod -``` - - - - - diff --git a/solution/2500-2599/2514.Count Anagrams/README_EN.md b/solution/2500-2599/2514.Count Anagrams/README_EN.md index 0f0409c3ae82d..49e1bdda20b57 100644 --- a/solution/2500-2599/2514.Count Anagrams/README_EN.md +++ b/solution/2500-2599/2514.Count Anagrams/README_EN.md @@ -70,23 +70,17 @@ tags: #### Python3 ```python -mod = 10**9 + 7 -f = [1] -for i in range(1, 10**5 + 1): - f.append(f[-1] * i % mod) - - class Solution: def countAnagrams(self, s: str) -> int: - ans = 1 + mod = 10**9 + 7 + ans = mul = 1 for w in s.split(): - cnt = Counter(w) - ans *= f[len(w)] - ans %= mod - for v in cnt.values(): - ans *= pow(f[v], -1, mod) - ans %= mod - return ans + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod ``` #### Java @@ -190,30 +184,4 @@ func pow(x, n int) int { - - -### Solution 2 - - - -#### Python3 - -```python -class Solution: - def countAnagrams(self, s: str) -> int: - mod = 10**9 + 7 - ans = mul = 1 - for w in s.split(): - cnt = Counter() - for i, c in enumerate(w, 1): - cnt[c] += 1 - mul = mul * cnt[c] % mod - ans = ans * i % mod - return ans * pow(mul, -1, mod) % mod -``` - - - - - diff --git a/solution/2500-2599/2514.Count Anagrams/Solution.py b/solution/2500-2599/2514.Count Anagrams/Solution.py index 204602441bdc2..60448951478f0 100644 --- a/solution/2500-2599/2514.Count Anagrams/Solution.py +++ b/solution/2500-2599/2514.Count Anagrams/Solution.py @@ -1,17 +1,11 @@ -mod = 10**9 + 7 -f = [1] -for i in range(1, 10**5 + 1): - f.append(f[-1] * i % mod) - - class Solution: def countAnagrams(self, s: str) -> int: - ans = 1 + mod = 10**9 + 7 + ans = mul = 1 for w in s.split(): - cnt = Counter(w) - ans *= f[len(w)] - ans %= mod - for v in cnt.values(): - ans *= pow(f[v], -1, mod) - ans %= mod - return ans + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod diff --git a/solution/2500-2599/2514.Count Anagrams/Solution2.py b/solution/2500-2599/2514.Count Anagrams/Solution2.py deleted file mode 100644 index 60448951478f0..0000000000000 --- a/solution/2500-2599/2514.Count Anagrams/Solution2.py +++ /dev/null @@ -1,11 +0,0 @@ -class Solution: - def countAnagrams(self, s: str) -> int: - mod = 10**9 + 7 - ans = mul = 1 - for w in s.split(): - cnt = Counter() - for i, c in enumerate(w, 1): - cnt[c] += 1 - mul = mul * cnt[c] % mod - ans = ans * i % mod - return ans * pow(mul, -1, mod) % mod diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md b/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md index 47bf5893704a2..1d001d2ab5505 100644 --- a/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md @@ -49,7 +49,7 @@ tags: 输入:nums = [1], k = 1 输出:1 解释:数组 nums 中的美丽数组有:[1] 。 -可以证明数组 [1] 中只存在 1 个美丽子集。 +可以证明数组 [1] 中只存在 1 个美丽子集。

 

@@ -69,16 +69,16 @@ tags: ### 方法一:计数 + 回溯 -我们用哈希表或数组 $cnt$ 记录当前已经选择的数字以及它们的个数,用 $ans$ 记录美丽子集的数目,初始时 $ans = -1$,表示排除空集。 +我们用哈希表或数组 $\textit{cnt}$ 记录当前已经选择的数字以及它们的个数,用 $\textit{ans}$ 记录美丽子集的数目,初始时 $\textit{ans} = -1$,表示排除空集。 -对于数组 $nums$ 中的每个数字 $x$,我们有两种选择: +对于数组 $\textit{nums}$ 中的每个数字 $x$,我们有两种选择: - 不选择 $x$,此时直接递归到下一个数字; -- 选择 $x$,此时需要判断 $x + k$ 和 $x - k$ 是否已经在 $cnt$ 中出现过,如果都没有出现过,那么我们就可以选择 $x$,此时我们将 $x$ 的个数加一,然后递归到下一个数字,最后将 $x$ 的个数减一。 +- 选择 $x$,此时需要判断 $x + k$ 和 $x - k$ 是否已经在 $\textit{cnt}$ 中出现过,如果都没有出现过,那么我们就可以选择 $x$,此时我们将 $x$ 的个数加一,然后递归到下一个数字,最后将 $x$ 的个数减一。 -最后,我们返回 $ans$ 即可。 +最后,我们返回 $\textit{ans}$ 即可。 -时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 +时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 @@ -147,7 +147,7 @@ public: int cnt[1010]{}; int n = nums.size(); - function dfs = [&](int i) { + auto dfs = [&](this auto&& dfs, int i) { if (i >= n) { ++ans; return; @@ -220,6 +220,36 @@ function beautifulSubsets(nums: number[], k: number): number { } ``` +#### C# + +```cs +public class Solution { + public int BeautifulSubsets(int[] nums, int k) { + int ans = -1; + int[] cnt = new int[1010]; + int n = nums.Length; + + void Dfs(int i) { + if (i >= n) { + ans++; + return; + } + Dfs(i + 1); + bool ok1 = nums[i] + k >= 1010 || cnt[nums[i] + k] == 0; + bool ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0; + if (ok1 && ok2) { + cnt[nums[i]]++; + Dfs(i + 1); + cnt[nums[i]]--; + } + } + + Dfs(0); + return ans; + } +} +``` + diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md b/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md index 509048f7ef96a..0749a5629c016 100644 --- a/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md @@ -67,16 +67,16 @@ It can be proved that there is only 1 beautiful subset in the array [1]. ### Solution 1: Counting + Backtracking -We use a hash table or an array $cnt$ to record the currently selected numbers and their counts, and use $ans$ to record the number of beautiful subsets, initially $ans = -1$, indicating that the empty set is excluded. +We use a hash table or array $\textit{cnt}$ to record the currently selected numbers and their counts, and use $\textit{ans}$ to record the number of beautiful subsets. Initially, $\textit{ans} = -1$ to exclude the empty set. -For each number $x$ in the array $nums$, we have two choices: +For each number $x$ in the array $\textit{nums}$, we have two choices: -- Do not choose $x$, and then directly recurse to the next number; -- Choose $x$, then we need to check whether $x + k$ and $x - k$ have appeared in $cnt$ before, if neither has appeared before, then we can choose $x$, at this time we add one to the number of $x$, and then recurse to the next number, and finally subtract one from the number of $x$. +- Do not select $x$, and directly recurse to the next number; +- Select $x$, and check if $x + k$ and $x - k$ have already appeared in $\textit{cnt}$. If neither has appeared, we can select $x$. In this case, we increment the count of $x$ by one, recurse to the next number, and then decrement the count of $x$ by one. -Finally, we return $ans$. +Finally, we return $\textit{ans}$. -Time complexity $O(2^n)$, space complexity $O(n)$, where $n$ is the length of the array $nums$. +The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $\textit{nums}$. @@ -145,7 +145,7 @@ public: int cnt[1010]{}; int n = nums.size(); - function dfs = [&](int i) { + auto dfs = [&](this auto&& dfs, int i) { if (i >= n) { ++ans; return; @@ -218,6 +218,36 @@ function beautifulSubsets(nums: number[], k: number): number { } ``` +#### C# + +```cs +public class Solution { + public int BeautifulSubsets(int[] nums, int k) { + int ans = -1; + int[] cnt = new int[1010]; + int n = nums.Length; + + void Dfs(int i) { + if (i >= n) { + ans++; + return; + } + Dfs(i + 1); + bool ok1 = nums[i] + k >= 1010 || cnt[nums[i] + k] == 0; + bool ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0; + if (ok1 && ok2) { + cnt[nums[i]]++; + Dfs(i + 1); + cnt[nums[i]]--; + } + } + + Dfs(0); + return ans; + } +} +``` + diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cpp b/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cpp index 7135b2e7a3176..db35a8fc1b841 100644 --- a/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cpp +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cpp @@ -5,7 +5,7 @@ class Solution { int cnt[1010]{}; int n = nums.size(); - function dfs = [&](int i) { + auto dfs = [&](this auto&& dfs, int i) { if (i >= n) { ++ans; return; @@ -22,4 +22,4 @@ class Solution { dfs(0); return ans; } -}; \ No newline at end of file +}; diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cs b/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cs new file mode 100644 index 0000000000000..ca374b0d68a81 --- /dev/null +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/Solution.cs @@ -0,0 +1,25 @@ +public class Solution { + public int BeautifulSubsets(int[] nums, int k) { + int ans = -1; + int[] cnt = new int[1010]; + int n = nums.Length; + + void Dfs(int i) { + if (i >= n) { + ans++; + return; + } + Dfs(i + 1); + bool ok1 = nums[i] + k >= 1010 || cnt[nums[i] + k] == 0; + bool ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0; + if (ok1 && ok2) { + cnt[nums[i]]++; + Dfs(i + 1); + cnt[nums[i]]--; + } + } + + Dfs(0); + return ans; + } +}