Lintcode 18 Subsets II__Lintcode

來源:互聯網
上載者:User

Question

Given a list of numbers that may has duplicate numbers, return all possible subsets.

Example

If S = [1,2,2], a solution is:

[ [2],

[1],

[1,2,2],

[2,2],

[1,2],

[] ]

Challenge

Can you do it in both recursively and iteratively? Solution

Recursion: 與Subsets 17類似,但是因為有重複元素,為了避免出現重複解,有幾點需要注意。

1) 將所有重複元素排在一起,因此首先對輸入數組進行排序

2) 避免重複的方法為:重複元素只能取第一個元素,因此在加入元素前要判斷該元素值是否和之前元素相等。

Non-Recursion:

代碼如下:

Recursion:

class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        List<List<Integer>> result = new ArrayList<>();        List<Integer> list = new ArrayList<>();        if(nums == null || nums.length == 0){ return result;}        Arrays.sort(nums);        helper(result, list, nums, 0);        return result;    }        public void helper( List<List<Integer>> result, List<Integer> list, int []nums, int index){                        if(!result.contains(list)){result.add(new ArrayList<>(list));}           // result.add(new ArrayList<>(list));            for( int i = index; i < nums.length ; i++){                list.add(nums[i]);                helper(result, list, nums, i+1);                list.remove(list.size() - 1);            }       }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.