原題:
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], []]這道題就是生成子集的問題,高中知識,子集個數為2^n個。所以我的思路是0-2^n的循環,然后將十進制數對應到二進制,根據二進制的值對應到某個元素是否在某個子集中。詳細代碼(代碼不好,速度有點慢,leetcode上有大神的代碼,估計C語言會快一點?):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其中十進制to二進制的代碼,求余求商,求出的結果是從低位到高位(對應學的十進制轉化二進制的方式,結果從下到上排列),上邊用的時候有些許變化:
n = 12PRint bin(n)while n != 0: print n%2 n = n/2其實python中有十進制到二進制轉化的函數: 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.
轉化為了字符串,10 - 0b1010,注意0b也是字符串的內容,所以真正的二進制字符串是從索引2開始的。
新聞熱點
疑難解答