From 1188a607ac5534838f60344b408752beb99337f4 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 19 Dec 2023 19:41:14 +0800 Subject: [PATCH] feat: add solutions to lc problems: No.1859+ --- .../1859.Sorting the Sentence/README.md | 82 +++--- .../1859.Sorting the Sentence/README_EN.md | 84 +++--- .../1859.Sorting the Sentence/Solution.cpp | 39 +-- .../1859.Sorting the Sentence/Solution.go | 9 +- .../1859.Sorting the Sentence/Solution.java | 21 +- .../1859.Sorting the Sentence/Solution.js | 9 +- .../1859.Sorting the Sentence/Solution.py | 15 +- .../1859.Sorting the Sentence/Solution.ts | 9 +- .../1860.Incremental Memory Leak/README.md | 4 +- .../1860.Incremental Memory Leak/README_EN.md | 12 + .../1861.Rotating the Box/README_EN.md | 6 + .../README.md | 254 +++++++++++++++--- .../README_EN.md | 254 +++++++++++++++--- .../Solution.cpp | 17 ++ .../Solution.go | 14 + .../Solution.java | 34 +-- .../Solution.js | 27 +- .../Solution.py | 26 +- .../Solution.ts | 14 + 19 files changed, 693 insertions(+), 237 deletions(-) create mode 100644 solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp create mode 100644 solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go create mode 100644 solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts diff --git a/solution/1800-1899/1859.Sorting the Sentence/README.md b/solution/1800-1899/1859.Sorting the Sentence/README.md index 21f5217a49229..7958fa6aa2971 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/README.md +++ b/solution/1800-1899/1859.Sorting the Sentence/README.md @@ -51,11 +51,13 @@ **方法一:字符串分割** -先将字符串 `s` 按照空格分割,得到字符串数组 `words`。 +我们先将字符串 $s$ 按照空格分割,得到字符串数组 $words$。然后,我们创建一个长度为 $|words|$ 的字符串数组 $ans$,用于存放答案。 -遍历字符串数组 `words`,提取 `words[i]` 中最后一位字符,将其转换为数字,得到 `words[i][0:len(words[i])-1]` 的实际位置。 +接下来,遍历字符串数组 $words$ 中的每个字符串 $w$,找到 $w$ 的最后一个字符表示的位置 $i$,然后将 $w$ 的前 $|w|-1$ 个字符作为新的字符串 $w'$,将 $w'$ 放在数组 $ans$ 的第 $i$ 个位置。 -时间复杂度 $O(n)$,其中 $n$ 是字符串长度。 +最后,将数组 $ans$ 按照空格连接成字符串,即为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 @@ -66,11 +68,18 @@ ```python class Solution: def sortSentence(self, s: str) -> str: - words = s.split() - ans = [None] * len(words) - for w in words: - i = int(w[-1]) - 1 - ans[i] = w[:-1] + ws = [(w[:-1], int(w[-1])) for w in s.split()] + ws.sort(key=lambda x: x[1]) + return ' '.join(w for w, _ in ws) +``` + +```python +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] return ' '.join(ans) ``` @@ -81,11 +90,12 @@ class Solution: ```java class Solution { public String sortSentence(String s) { - String[] words = s.split(" "); - String[] ans = new String[words.length]; - for (String w : words) { - int i = w.charAt(w.length() - 1) - '1'; - ans[i] = w.substring(0, w.length() - 1); + String[] ws = s.split(" "); + int n = ws.length; + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + String w = ws[i]; + ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1); } return String.join(" ", ans); } @@ -98,17 +108,18 @@ class Solution { class Solution { public: string sortSentence(string s) { - istringstream is(s); - string t; - vector words; - while (is >> t) words.push_back(t); - vector res(words.size()); - for (auto& w : words) { - int i = w[w.size() - 1] - '1'; - res[i] = w.substr(0, w.size() - 1); + istringstream iss(s); + string w; + vector ws; + while (iss >> w) { + ws.push_back(w); + } + vector ss(ws.size()); + for (auto& w : ws) { + ss[w.back() - '1'] = w.substr(0, w.size() - 1); } string ans; - for (auto& w : res) { + for (auto& w : ss) { ans += w + " "; } ans.pop_back(); @@ -121,11 +132,10 @@ public: ```go func sortSentence(s string) string { - words := strings.Split(s, " ") - ans := make([]string, len(words)) - for _, w := range words { - i := w[len(w)-1] - '1' - ans[i] = w[:len(w)-1] + ws := strings.Split(s, " ") + ans := make([]string, len(ws)) + for _, w := range ws { + ans[w[len(w)-1]-'1'] = w[:len(w)-1] } return strings.Join(ans, " ") } @@ -139,11 +149,10 @@ func sortSentence(s string) string { * @return {string} */ var sortSentence = function (s) { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); }; @@ -153,11 +162,10 @@ var sortSentence = function (s) { ```ts function sortSentence(s: string): string { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); } diff --git a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md index def90c540ee4c..0b57e23b45781 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md +++ b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md @@ -44,6 +44,16 @@ ## Solutions +**Solution 1: String Splitting** + +First, we split the string $s$ by spaces to get the string array $words$. Then, we create a string array $ans$ of length $|words|$ to store the answer. + +Next, we iterate over each string $w$ in the string array $words$, find the position $i$ represented by the last character of $w$, then take the first $|w|-1$ characters of $w$ as the new string $w'$, and place $w'$ in the $i$th position of the array $ans$. + +Finally, we join the array $ans$ into a string by spaces, which is the answer. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. + ### **Python3** @@ -51,11 +61,18 @@ ```python class Solution: def sortSentence(self, s: str) -> str: - words = s.split() - ans = [None] * len(words) - for w in words: - i = int(w[-1]) - 1 - ans[i] = w[:-1] + ws = [(w[:-1], int(w[-1])) for w in s.split()] + ws.sort(key=lambda x: x[1]) + return ' '.join(w for w, _ in ws) +``` + +```python +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] return ' '.join(ans) ``` @@ -64,11 +81,12 @@ class Solution: ```java class Solution { public String sortSentence(String s) { - String[] words = s.split(" "); - String[] ans = new String[words.length]; - for (String w : words) { - int i = w.charAt(w.length() - 1) - '1'; - ans[i] = w.substring(0, w.length() - 1); + String[] ws = s.split(" "); + int n = ws.length; + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + String w = ws[i]; + ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1); } return String.join(" ", ans); } @@ -81,17 +99,18 @@ class Solution { class Solution { public: string sortSentence(string s) { - istringstream is(s); - string t; - vector words; - while (is >> t) words.push_back(t); - vector res(words.size()); - for (auto& w : words) { - int i = w[w.size() - 1] - '1'; - res[i] = w.substr(0, w.size() - 1); + istringstream iss(s); + string w; + vector ws; + while (iss >> w) { + ws.push_back(w); + } + vector ss(ws.size()); + for (auto& w : ws) { + ss[w.back() - '1'] = w.substr(0, w.size() - 1); } string ans; - for (auto& w : res) { + for (auto& w : ss) { ans += w + " "; } ans.pop_back(); @@ -104,11 +123,10 @@ public: ```go func sortSentence(s string) string { - words := strings.Split(s, " ") - ans := make([]string, len(words)) - for _, w := range words { - i := w[len(w)-1] - '1' - ans[i] = w[:len(w)-1] + ws := strings.Split(s, " ") + ans := make([]string, len(ws)) + for _, w := range ws { + ans[w[len(w)-1]-'1'] = w[:len(w)-1] } return strings.Join(ans, " ") } @@ -122,11 +140,10 @@ func sortSentence(s string) string { * @return {string} */ var sortSentence = function (s) { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); }; @@ -136,11 +153,10 @@ var sortSentence = function (s) { ```ts function sortSentence(s: string): string { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); } diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp index 1f13c6dde845e..01a8e1017d68e 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.cpp @@ -1,20 +1,21 @@ -class Solution { -public: - string sortSentence(string s) { - istringstream is(s); - string t; - vector words; - while (is >> t) words.push_back(t); - vector res(words.size()); - for (auto& w : words) { - int i = w[w.size() - 1] - '1'; - res[i] = w.substr(0, w.size() - 1); - } - string ans; - for (auto& w : res) { - ans += w + " "; - } - ans.pop_back(); - return ans; - } +class Solution { +public: + string sortSentence(string s) { + istringstream iss(s); + string w; + vector ws; + while (iss >> w) { + ws.push_back(w); + } + vector ss(ws.size()); + for (auto& w : ws) { + ss[w.back() - '1'] = w.substr(0, w.size() - 1); + } + string ans; + for (auto& w : ss) { + ans += w + " "; + } + ans.pop_back(); + return ans; + } }; \ No newline at end of file diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.go b/solution/1800-1899/1859.Sorting the Sentence/Solution.go index 20517960bd125..e0d069b026b2d 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.go +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.go @@ -1,9 +1,8 @@ func sortSentence(s string) string { - words := strings.Split(s, " ") - ans := make([]string, len(words)) - for _, w := range words { - i := w[len(w)-1] - '1' - ans[i] = w[:len(w)-1] + ws := strings.Split(s, " ") + ans := make([]string, len(ws)) + for _, w := range ws { + ans[w[len(w)-1]-'1'] = w[:len(w)-1] } return strings.Join(ans, " ") } \ No newline at end of file diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.java b/solution/1800-1899/1859.Sorting the Sentence/Solution.java index 6389492d7032b..cea8b91864566 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.java +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.java @@ -1,11 +1,12 @@ -class Solution { - public String sortSentence(String s) { - String[] words = s.split(" "); - String[] ans = new String[words.length]; - for (String w : words) { - int i = w.charAt(w.length() - 1) - '1'; - ans[i] = w.substring(0, w.length() - 1); - } - return String.join(" ", ans); - } +class Solution { + public String sortSentence(String s) { + String[] ws = s.split(" "); + int n = ws.length; + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + String w = ws[i]; + ans[w.charAt(w.length() - 1) - '1'] = w.substring(0, w.length() - 1); + } + return String.join(" ", ans); + } } \ No newline at end of file diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.js b/solution/1800-1899/1859.Sorting the Sentence/Solution.js index 10608d1f73cd6..f1ad9eb287de3 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.js +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.js @@ -3,11 +3,10 @@ * @return {string} */ var sortSentence = function (s) { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); }; diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.py b/solution/1800-1899/1859.Sorting the Sentence/Solution.py index 3e9cfbfe3a495..bac4af524fec8 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.py +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.py @@ -1,8 +1,7 @@ -class Solution: - def sortSentence(self, s: str) -> str: - words = s.split() - ans = [None] * len(words) - for w in words: - i = int(w[-1]) - 1 - ans[i] = w[:-1] - return ' '.join(ans) +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] + return " ".join(ans) diff --git a/solution/1800-1899/1859.Sorting the Sentence/Solution.ts b/solution/1800-1899/1859.Sorting the Sentence/Solution.ts index 8baf02269b8ef..8c691873a4a97 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/Solution.ts +++ b/solution/1800-1899/1859.Sorting the Sentence/Solution.ts @@ -1,9 +1,8 @@ function sortSentence(s: string): string { - const words = s.split(' '); - const ans = new Array(words.length); - for (const w of words) { - const i = w.charCodeAt(w.length - 1) - '1'.charCodeAt(0); - ans[i] = w.slice(0, w.length - 1); + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); } return ans.join(' '); } diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README.md b/solution/1800-1899/1860.Incremental Memory Leak/README.md index a52b5a27554ba..1fd6ff6c99677 100644 --- a/solution/1800-1899/1860.Incremental Memory Leak/README.md +++ b/solution/1800-1899/1860.Incremental Memory Leak/README.md @@ -51,7 +51,7 @@ **方法一:模拟** -直接模拟内存的分配。 +我们直接模拟内存的分配。 假设 $t$ 为意外退出的时刻,那么两个内存条一定可以容纳 $t-1$ 时刻及以前消耗的内存,因此有: @@ -59,7 +59,7 @@ $$ \sum_{i=1}^{t-1} i = \frac{t\times (t-1)}{2} \leq (m_1+m_2) $$ -时间复杂度 $O(\sqrt{m1+m2})$,其中 $m_1$, $m_2$ 分别为两个内存条的内存大小。 +时间复杂度 $O(\sqrt{m_1+m_2})$,其中 $m_1$, $m_2$ 分别为两个内存条的内存大小。 diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md index 10fe24c658f3c..169841f2bb8ad 100644 --- a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md +++ b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md @@ -45,6 +45,18 @@ ## Solutions +**Solution 1: Simulation** + +We directly simulate the allocation of memory. + +Assume $t$ is the moment of unexpected exit, then the two memory sticks can definitely accommodate the memory consumed at the moment $t-1$ and before, so we have: + +$$ +\sum_{i=1}^{t-1} i = \frac{t\times (t-1)}{2} \leq (m_1+m_2) +$$ + +The time complexity is $O(\sqrt{m_1+m_2})$, where $m_1$ and $m_2$ are the sizes of the two memory sticks respectively. + ### **Python3** diff --git a/solution/1800-1899/1861.Rotating the Box/README_EN.md b/solution/1800-1899/1861.Rotating the Box/README_EN.md index 3a9e765927fa7..beb5e46d8c82a 100644 --- a/solution/1800-1899/1861.Rotating the Box/README_EN.md +++ b/solution/1800-1899/1861.Rotating the Box/README_EN.md @@ -71,6 +71,12 @@ ## Solutions +**Solution 1: Queue Simulation** + +First, we rotate the matrix 90 degrees clockwise, then simulate the falling process of the stones in each column. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively. + ### **Python3** diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md index ec94b7dcc59d6..705002837f323 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md @@ -68,6 +68,27 @@ +**方法一:二进制枚举** + +我们可以用二进制枚举的方法,枚举出所有的子集,然后计算每个子集的异或总和。 + +具体地,我们在 $[0, 2^n)$ 的范围内枚举 $i$,其中 $n$ 是数组 $nums$ 的长度。如果 $i$ 的二进制表示的第 $j$ 位为 $1$,那么代表着 $nums$ 的第 $j$ 个元素在当前枚举的子集中;如果第 $j$ 位为 $0$,那么代表着 $nums$ 的第 $j$ 个元素不在当前枚举的子集中。我们可以根据 $i$ 的二进制表示,得到当前子集对应的异或总和,将其加到答案中即可。 + +时间复杂度 $O(n \times 2^n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 + +**方法二:DFS** + +我们也可以使用深度优先搜索的方法,枚举出所有的子集,然后计算每个子集的异或总和。 + +我们设计一个函数 $dfs(i, s)$,其中 $i$ 表示当前搜索到数组 $nums$ 的第 $i$ 个元素,$s$ 表示当前子集的异或总和。初始时,$i=0$, $s=0$。在搜索的过程中,每次我们都有两种选择: + +- 将 $nums$ 的第 $i$ 个元素加入当前子集,即 $dfs(i+1, s \oplus nums[i])$; +- 将 $nums$ 的第 $i$ 个元素不加入当前子集,即 $dfs(i+1, s)$。 + +当我们搜索完数组 $nums$ 的所有元素时,即 $i=n$ 时,当前子集的异或总和为 $s$,将其加到答案中即可。 + +时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + ### **Python3** @@ -77,17 +98,30 @@ ```python class Solution: def subsetXORSum(self, nums: List[int]) -> int: - def dfs(nums, depth, prev): - self.res += prev - for num in nums[depth:]: - prev ^= num - depth += 1 - dfs(nums, depth, prev) - prev ^= num - - self.res = 0 - dfs(nums, 0, 0) - return self.res + ans, n = 0, len(nums) + for i in range(1 << n): + s = 0 + for j in range(n): + if i >> j & 1: + s ^= nums[j] + ans += s + return ans +``` + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans ``` ### **Java** @@ -96,24 +130,158 @@ class Solution: ```java class Solution { - private int res; + public int subsetXORSum(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +} +``` + +```java +class Solution { + private int ans; + private int[] nums; public int subsetXORSum(int[] nums) { - dfs(nums, 0, 0); - return res; + this.nums = nums; + dfs(0, 0); + return ans; } - private void dfs(int[] nums, int depth, int prev) { - res += prev; - for (int i = depth; i < nums.length; ++i) { - prev ^= nums[i]; - dfs(nums, ++depth, prev); - prev ^= nums[i]; + private void dfs(int i, int s) { + if (i >= nums.length) { + ans += s; + return; } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); } } ``` +### **C++** + +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +}; +``` + +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + function dfs = [&](int i, int s) { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; + } +}; +``` + +### **Go** + +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + for i := 0; i < 1<>j&1 == 1 { + s ^= x + } + } + ans += s + } + return +} +``` + +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + var dfs func(int, int) + dfs = func(i, s int) { + if i >= n { + ans += s + return + } + dfs(i+1, s) + dfs(i+1, s^nums[i]) + } + dfs(0, 0) + return +} +``` + +### **TypeScript** + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; +} +``` + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + const dfs = (i: number, s: number) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +} +``` + ### **JavaScript** ```js @@ -122,22 +290,40 @@ class Solution { * @return {number} */ var subsetXORSum = function (nums) { - let res = []; - let prev = 0; - dfs(nums, 0, prev, res); - return res.reduce((a, c) => a + c, 0); + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; }; +``` -function dfs(nums, depth, prev, res) { - res.push(prev); - for (let i = depth; i < nums.length; i++) { - prev ^= nums[i]; - depth++; - dfs(nums, depth, prev, res); - // bracktrack - prev ^= nums[i]; - } -} +```js +/** + * @param {number[]} nums + * @return {number} + */ +var subsetXORSum = function (nums) { + let ans = 0; + const n = nums.length; + const dfs = (i, s) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +}; ``` ### **...** diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md index 0ddce174f9165..7c9c5b68cea25 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md @@ -65,6 +65,27 @@ ## Solutions +**Solution 1: Binary Enumeration** + +We can use binary enumeration to enumerate all subsets, and then calculate the XOR sum of each subset. + +Specifically, we enumerate $i$ in the range $[0, 2^n)$, where $n$ is the length of the array $nums$. If the $j$th bit of the binary representation of $i$ is $1$, it means that the $j$th element of $nums$ is in the current subset; if the $j$th bit is $0$, it means that the $j$th element of $nums$ is not in the current subset. We can get the XOR sum of the current subset according to the binary representation of $i$, and add it to the answer. + +The time complexity is $O(n \times 2^n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + +**Solution 2: DFS (Depth-First Search)** + +We can also use depth-first search to enumerate all subsets, and then calculate the XOR sum of each subset. + +We design a function $dfs(i, s)$, where $i$ represents the current search to the $i$th element of the array $nums$, and $s$ represents the XOR sum of the current subset. Initially, $i=0$, $s=0$. During the search, we have two choices each time: + +- Add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s \oplus nums[i])$; +- Do not add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s)$. + +When we have searched all elements of the array $nums$, i.e., $i=n$, the XOR sum of the current subset is $s$, and we can add it to the answer. + +The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. + ### **Python3** @@ -72,38 +93,185 @@ ```python class Solution: def subsetXORSum(self, nums: List[int]) -> int: - def dfs(nums, depth, prev): - self.res += prev - for num in nums[depth:]: - prev ^= num - depth += 1 - dfs(nums, depth, prev) - prev ^= num - - self.res = 0 - dfs(nums, 0, 0) - return self.res + ans, n = 0, len(nums) + for i in range(1 << n): + s = 0 + for j in range(n): + if i >> j & 1: + s ^= nums[j] + ans += s + return ans +``` + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans ``` ### **Java** ```java class Solution { - private int res; + public int subsetXORSum(int[] nums) { + int n = nums.length; + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +} +``` + +```java +class Solution { + private int ans; + private int[] nums; public int subsetXORSum(int[] nums) { - dfs(nums, 0, 0); - return res; + this.nums = nums; + dfs(0, 0); + return ans; + } + + private void dfs(int i, int s) { + if (i >= nums.length) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; } +}; +``` + +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + function dfs = [&](int i, int s) { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; + } +}; +``` + +### **Go** - private void dfs(int[] nums, int depth, int prev) { - res += prev; - for (int i = depth; i < nums.length; ++i) { - prev ^= nums[i]; - dfs(nums, ++depth, prev); - prev ^= nums[i]; +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + for i := 0; i < 1<>j&1 == 1 { + s ^= x + } + } + ans += s + } + return +} +``` + +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + var dfs func(int, int) + dfs = func(i, s int) { + if i >= n { + ans += s + return + } + dfs(i+1, s) + dfs(i+1, s^nums[i]) + } + dfs(0, 0) + return +} +``` + +### **TypeScript** + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } } + ans += s; } + return ans; +} +``` + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + const dfs = (i: number, s: number) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; } ``` @@ -115,22 +283,40 @@ class Solution { * @return {number} */ var subsetXORSum = function (nums) { - let res = []; - let prev = 0; - dfs(nums, 0, prev, res); - return res.reduce((a, c) => a + c, 0); + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; }; +``` -function dfs(nums, depth, prev, res) { - res.push(prev); - for (let i = depth; i < nums.length; i++) { - prev ^= nums[i]; - depth++; - dfs(nums, depth, prev, res); - // bracktrack - prev ^= nums[i]; - } -} +```js +/** + * @param {number[]} nums + * @return {number} + */ +var subsetXORSum = function (nums) { + let ans = 0; + const n = nums.length; + const dfs = (i, s) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +}; ``` ### **...** diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp new file mode 100644 index 0000000000000..96a107b07cad6 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go new file mode 100644 index 0000000000000..84693f1999b84 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.go @@ -0,0 +1,14 @@ +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + var dfs func(int, int) + dfs = func(i, s int) { + if i >= n { + ans += s + return + } + dfs(i+1, s) + dfs(i+1, s^nums[i]) + } + dfs(0, 0) + return +} \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java index 0de7bcd98218d..4bf80cd0de29a 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.java @@ -1,17 +1,19 @@ -class Solution { - private int res; - - public int subsetXORSum(int[] nums) { - dfs(nums, 0, 0); - return res; - } - - private void dfs(int[] nums, int depth, int prev) { - res += prev; - for (int i = depth; i < nums.length; ++i) { - prev ^= nums[i]; - dfs(nums, ++depth, prev); - prev ^= nums[i]; - } - } +class Solution { + private int ans; + private int[] nums; + + public int subsetXORSum(int[] nums) { + this.nums = nums; + dfs(0, 0); + return ans; + } + + private void dfs(int i, int s) { + if (i >= nums.length) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + } } \ No newline at end of file diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js index 37832de9befcd..ba314b524a976 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.js @@ -3,19 +3,16 @@ * @return {number} */ var subsetXORSum = function (nums) { - let res = []; - let prev = 0; - dfs(nums, 0, prev, res); - return res.reduce((a, c) => a + c, 0); + let ans = 0; + const n = nums.length; + const dfs = (i, s) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; }; - -function dfs(nums, depth, prev, res) { - res.push(prev); - for (let i = depth; i < nums.length; i++) { - prev ^= nums[i]; - depth++; - dfs(nums, depth, prev, res); - // bracktrack - prev ^= nums[i]; - } -} diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py index a2f9a779f8341..2e180076e0817 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.py @@ -1,13 +1,13 @@ -class Solution: - def subsetXORSum(self, nums: List[int]) -> int: - def dfs(nums, depth, prev): - self.res += prev - for num in nums[depth:]: - prev ^= num - depth += 1 - dfs(nums, depth, prev) - prev ^= num - - self.res = 0 - dfs(nums, 0, 0) - return self.res +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts new file mode 100644 index 0000000000000..8bd8da85b5597 --- /dev/null +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution.ts @@ -0,0 +1,14 @@ +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + const dfs = (i: number, s: number) => { + if (i >= n) { + ans += s; + return; + } + dfs(i + 1, s); + dfs(i + 1, s ^ nums[i]); + }; + dfs(0, 0); + return ans; +}