Leetcode 90 Subsets II

Given a collection of integers that might contain duplicates, 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,2], a solution is:

[

  [2],

  [1],

  [1,2,2],

  [2,2],

  [1,2],

  []

]

Leetcode 78 Subsets

区别在于这边需要临时搭一个数组的复制,单次只能去掉一个元素而不是使用 ans - [x] 去除ans内所有为x的元素。

def subsets_with_dup(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].dup

            temp.length.times do |j|

                if temp[j] == x

                    temp.delete_at(j) 

                    break

                end

            end

            ans << temp unless ans.include?(temp)

        end

    end

    return ans if ans[-1].empty?

    sub(ans,t)

end

 

你可能感兴趣的:(LeetCode)