python列出集合中的所有子集(总结)

我们不生产答案,只是大神的搬运工,嘿嘿。

  1. 库函数
for a in range(len(list1)):
    for i in combinations(list1, a+1):
            print(i)
  1. 二进制位运算
def PowerSetsBinary(items):
    N = len(items)
    for i in range(2 ** N):#子集的个数
        combo = []
        for j in range(N):#用来判断二进制数的下标为j的位置的数是否为1
            if (i >> j) % 2:#模2判断二进制的最后一个数是否为1
                combo.append(items[j])
        print(combo)

原作者地址

  1. 反向位运算
def combinations(str):
    n=1<<len(str)
    for i in range(n):
        bits=[i>>offset&1 for offset in range(len(str)-1,-1,-1)]
        current=[str[index] for (index,bit) in enumerate(bits) if bit==1]
        print(''.join(current));

下面的方法都是来自于LeetCode的子集这个题目
4. 递归

def subsets(nums: List[int]) -> List[List[int]]:
        n = len(nums)
        output = [[]]

        for num in nums:
            output += [curr + [num] for curr in output]
        print(output)     
  1. 回溯
def subsets(nums: List[int]) -> List[List[int]]:
    def backtrack(first = 0, curr = []):
        # if the combination is done
        if len(curr) == k:  
            output.append(curr[:])
        for i in range(first, n):
            # add nums[i] into the current combination
            curr.append(nums[i])
            # use next integers to complete the combination
            backtrack(i + 1, curr)
            # backtrack
            curr.pop()
    
    output = []
    n = len(nums)
    for k in range(n + 1):
        backtrack()
    print(output)
  1. 字典排序(二进制排序) 子集
def subsets(nums: List[int]) -> List[List[int]]:
    n = len(nums)
    output = []
    
    for i in range(2**n, 2**(n + 1)):
        # generate bitmask, from 0..00 to 1..11
        bitmask = bin(i)[3:]
        # append subset corresponding to that bitmask
        output.append([nums[j] for j in range(n) if bitmask[j] == '1'])
    print(output)
  1. 迭代
def subsets(nums: List[int]) -> List[List[int]]:
        res = [[]]
        for i in nums:
            res = res + [[i] + num for num in res]
        print(res)

  1. 递归(回溯算法)
def subsets(nums: List[int]) -> List[List[int]]:
        res = []
        n = len(nums)
        
        def helper(i, tmp):
            res.append(tmp)
            for j in range(i, n):
                helper(j + 1,tmp + [nums[j]] )
        helper(0, [])
        print(res)

另附一个Java版的解法,个人使用来看的话,这个Java版的效率更高,但是苦于不知道怎么用Python实现。

public static void main(String[] args) {
     

        String str[] = {
      "A", "B", "C", "D", "E" };

        int nCnt = str.length;

        int nBit = (0xFFFFFFFF >>> (32 - nCnt));

        for (int i = 1; i <= nBit; i++) {
     
            for (int j = 0; j < nCnt; j++) {
     
                if ((i << (31 - j)) >> 31 == -1) {
     
                    System.out.print(str[j]);
                }
            }
            System.out.println("");
        }

    }

原作者地址

你可能感兴趣的:(python列出集合中的所有子集(总结))