139 - 78 子集
题目
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
解答
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
def helper(level, temp):
res.append(temp)
for i in range(level, len(nums)):
helper(i+1, temp+[nums[i]])
helper(0, [])
return res
Runtime: 28 ms, faster than 99.44% of Python3 online submissions for Subsets.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Subsets.
var subsets = function(nums) {
const ans = []
const helper = function(level, temp) {
ans.push(temp)
for (let i = level; i < nums.length; i++) {
const next = temp.slice()
next.push(nums[i])
helper(i + 1, next)
}
}
helper(0, [])
return ans
};
Runtime: 60 ms, faster than 68.85% of JavaScript online submissions for Subsets.
Memory Usage: 34.9 MB, less than 47.06% of JavaScript online submissions for Subsets.
func subsets(nums []int) [][]int {
ans := make([][]int, 0)
var helper func(int, []int)
helper = func(level int, temp []int) {
ans = append(ans, temp)
for i := level; i < len(nums); i++ {
next := make([]int, len(temp))
copy(next, temp)
next = append(next, nums[i])
helper(i+1, next)
}
}
helper(0, []int{})
return ans
}
Runtime: 0 ms, faster than 100.00% of Go online submissions for Subsets.
Memory Usage: 6.8 MB, less than 50.00% of Go online submissions for Subsets.
Last updated
Was this helpful?