Leetcode 78 Subsets

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

 递归:先排序数组,然后对于每个集合减去其中一个元素,在保证其唯一的情况下加入数组,并记载当前数组长度。

在下一次递归中,在ans数组中开始需要减去元素的集合index为之前ans数组的长度。终止条件为最后生成了空集合。

def subsets(nums)
    sub([nums.sort],0)
end

def sub(ans,start=0)
    t = ans.length
    (start...t).each do |i|
        ans[i].each do |x|
            temp = ans[i] - [x]
            ans << temp unless ans.include?(temp)
        end
    end
    return ans if ans[-1].empty?
    sub(ans,t)
end

 

 
posted @ 2015-07-12 09:29  lilixu  阅读(331)  评论(0编辑  收藏  举报