LeetCode刷題筆錄Subsets II

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

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
比Subsets要求稍高的一點是這裏會出現duplicate elements。想法是如果下一個元素是duplicate,那麼在下一次循環中就不是遍歷之前所有的solution set,而是隻遍歷前一次循環中新增加的Solution sets。以[1,2,2]爲例:

start: []

itr1: [] [1]

itr2:[] [1] [2] [1,2]

如果itr3按照之前的做法對每個set都加入新的元素2,那麼會產生重複:

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

可以看到只有[1,2,2]和[2,2]是我們需要新加入的solution set。

因此itr3只應該循環前一次循環新增加的部分

代碼如下:

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] num) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(num == null || num.length == 0)
            return res;
        Arrays.sort(num);
        res.add(new ArrayList<Integer>());
        
        int start = 0;
        for(int i = 0; i < num.length; i++){
            int size = res.size();
            for(int j = start; j < size; j++){
                List<Integer> sol = new ArrayList<Integer>(res.get(j));
                sol.add(num[i]);
                res.add(sol);
            }
            
            if(i < num.length - 1 && num[i] == num[i + 1])
                start = size;
            else
                start = 0;
        }
        
        return res;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章