国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

[LeetCode]78.Subsets

2019-11-11 01:54:38
字體:
供稿:網(wǎng)友

原題:

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,If nums = [1,2,3], a solution is:

[  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]這道題就是生成子集的問題,高中知識(shí),子集個(gè)數(shù)為2^n個(gè)。所以我的思路是0-2^n的循環(huán),然后將十進(jìn)制數(shù)對(duì)應(yīng)到二進(jìn)制,根據(jù)二進(jìn)制的值對(duì)應(yīng)到某個(gè)元素是否在某個(gè)子集中。詳細(xì)代碼(代碼不好,速度有點(diǎn)慢,leetcode上有大神的代碼,估計(jì)C語言會(huì)快一點(diǎn)?):

class Solution(object):    def subsets(self, nums):        """        :type nums: List[int]        :rtype: List[List[int]]        """        length = len(nums)  # size of nums        result = []         if length == 0:            return result        for x in xrange(0, 2**length):            s = bin(x)            sub = []            n = x            # decimal to binary            for i in xrange(0, length):                if n == 0:                    break                else:                    if n % 2 == 1:                        sub.append(nums[i])                    n = n / 2            result.append(sub)        return result

其中十進(jìn)制to二進(jìn)制的代碼,求余求商,求出的結(jié)果是從低位到高位(對(duì)應(yīng)學(xué)的十進(jìn)制轉(zhuǎn)化二進(jìn)制的方式,結(jié)果從下到上排列),上邊用的時(shí)候有些許變化:

n = 12PRint bin(n)while n != 0:    print n%2    n = n/2其實(shí)python中有十進(jìn)制到二進(jìn)制轉(zhuǎn)化的函數(shù): bin()

bin(x)Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

轉(zhuǎn)化為了字符串,10 - 0b1010,注意0b也是字符串的內(nèi)容,所以真正的二進(jìn)制字符串是從索引2開始的。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 大埔区| 师宗县| 镇原县| 宁远县| 大安市| 锡林浩特市| 新龙县| 衢州市| 绥滨县| 宜春市| 特克斯县| 股票| 焉耆| 乌兰察布市| 西藏| 开江县| 荥阳市| 朝阳区| 乡城县| 藁城市| 安丘市| 洛扎县| 疏附县| 土默特右旗| 金寨县| 沅江市| 芮城县| 阳信县| 丽水市| 白河县| 满城县| 石家庄市| 东莞市| 高邑县| 古蔺县| 宝应县| 潞西市| 泉州市| 呈贡县| 收藏| 察雅县|