[leetcode]Subsets @ Python

原题地址:https://oj.leetcode.com/problems/subsets/

题意:枚举所有子集。

解题思路:碰到这种问题,一律dfs。

代码:


class Solution:
# @param S, a list of integer
# @return a list of lists of integer

def subsets(self, S):
def dfs(depth, start, valuelist):
res.append(valuelist)
if depth == len(S): return
for i in range(start, len(S)):
dfs(depth+1, i+1, valuelist+[S[i]])
S.sort()
res = []
dfs(0, 0, [])
return res

[leetcode]Subsets @ Python

时间: 2024-08-24 17:26:59

[leetcode]Subsets @ Python的相关文章

[leetcode]Subsets II @ Python

原题地址:https://oj.leetcode.com/problems/subsets-ii/ 题意: Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicat

[LeetCode] Subsets [31]

题目 Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3]

[leetcode]Candy @ Python

原题地址:https://oj.leetcode.com/problems/candy/ 题意: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy

leetcode: Subsets & Subsets II

SubsetsGiven a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2

LeetCode Subsets II (DFS)

题意: 给一个集合,有n个可能相同的元素,求出所有的子集(包括空集,但是不能重复). 思路: 看这个就差不多了.LEETCODE SUBSETS (DFS) 1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 sort(nums.begin(),nums.end()); 5 DFS(0,nums,tmp); 6 ans.push_back(vector

[leetcode]4Sum @ Python

原题地址:http://oj.leetcode.com/problems/4sum/ 题意:从数组中找到4个数,使它们的和为target.要求去重,可能有多组解,需要都找出来. 解题思路:一开始想要像3Sum那样去解题,时间复杂度为O(N^3),可无论怎么写都是Time Limited Exceeded.而同样的算法使用C++是可以通过的.说明Python的执行速度比C++慢很多.还说明了一点,大概出题人的意思不是要让我们去像3Sum那样去解题,否则这道题就出的没有意义了.这里参考了kitt的解

[leetcode]Anagrams @ Python

原题地址:https://oj.leetcode.com/problems/anagrams/ 题意: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. 解题思路:anagram的意思是:abc,bac,acb就是anagram.即同一段字符串的字母的不同排序.将这些都找出来.这里使用了哈希表,即Python中的dic

LeetCode: Subsets II [091]

[题目] Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solutio

Leetcode:Subsets 求数组的所有子集

Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [