2 回答

TA貢獻1859條經(jīng)驗 獲得超6個贊
實際上,您正在復制切片,而不是數(shù)組。切片是數(shù)組段的描述符。它由指向數(shù)組的指針、段的長度及其容量(段的最大長度)組成。這意味著,您只是在創(chuàng)建切片標題的副本。底層數(shù)組仍然是共享的。 https://blog.golang.org/slices-intro

TA貢獻1829條經(jīng)驗 獲得超9個贊
這是 Go 中數(shù)組和切片的一個非常常見的問題(這與 Python 和 JavaScript 中的不同)。你會習慣的,這個答案也已經(jīng)解釋過了。
當然,這里也解釋了解決方案,我想你會知道它是如何工作的。
這將使用回溯傳入 Go (實現(xiàn)起來更簡單):
func subsets(nums []int) [][]int {
subs := make([][]int, 0)
backtrack(nums, 0, nil, &subs)
return subs
}
func backtrack(nums []int, index int, sub []int, subs *[][]int) {
if index == len(nums) {
*subs = append(*subs, append([]int{}, sub...))
return
}
backtrack(nums, index+1, sub, subs)
backtrack(nums, index+1, append(sub, nums[index]), subs)
}
同樣在Java中,
public final class Solution {
public static final List<List<Integer>> subsets(
final int[] nums
) {
List<List<Integer>> subs = new ArrayList<>();
Arrays.sort(nums);
backtrack(subs, new ArrayList<>(), nums, 0);
return subs;
}
private static void backtrack(
final List<List<Integer>> subs,
final List<Integer> sub,
final int[] nums,
final int start
) {
subs.add(new ArrayList<>(sub));
for (int index = start; index < nums.length; index++) {
sub.add(nums[index]);
backtrack(subs, sub, nums, index + 1);
sub.remove(sub.size() - 1);
}
}
}
迭代地,它會去(例如,使用 C++):
// The following block might trivially improve the exec time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
using ValueType = std::uint_fast16_t;
static const struct Solution {
static const std::vector<std::vector<int>> subsets(
const std::vector<int>& nums
) {
std::vector<std::vector<int>> subs = {{}};
ValueType subs_len;
for (const auto& num : nums) {
subs_len = std::size(subs);
for (ValueType len = 0; len < subs_len; ++len) {
subs.emplace_back(subs[len]);
subs.back().emplace_back(num);
}
}
return subs;
}
};
Python 還有一個combinations工具可以讓它變得簡單:
class Solution:
def subsets(self, nums):
return (tuple(j) for i in range(len(nums) + 1) for j in itertools.combinations(nums, i))
- 2 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報