Subsets II

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

 
class Solution {
    /**
     * @param S: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> S) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (S == null || S.size() == 0){
            return result;
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        Collections.sort(S);
        subsetsHelper(result, list, S, 0);
        return result;
    }
    
    private void subsetsHelper(ArrayList<ArrayList<Integer>> result,
                              ArrayList<Integer> list,
                              ArrayList<Integer> S,
                              int pos){
        result.add(new ArrayList<Integer>(list));
        for(int i = pos; i < S.size(); i++){
            if(pos != i && S.get(i) == S.get(i-1)){
                continue;
            }
            list.add(S.get(i));
            subsetsHelper(result, list, S, i+1);
            list.remove(list.size() - 1);
        }
    }
}

这道题和subset一样,都属于排列组合问题, 可以套用模版。

只是有些情况需要跳过: 当后面的数字和前面的数字重合(S.get(i) == S.get(i-1))同时又不是第一次加入数列(pos != i),不需要加入。 

e.g. []-> [1, 2(1)]->[1, 2(1), 2(2)]->[1, 2(1), 2(2), 2(3)] ,第一次加每个2的时候, pos=i。但继续去掉2(3), [1, 2(1), 2(3)]时候, (pos=2, i=3) && (S.get[2] ==S.get(3) ==2), 跳过。  

这道题不需要考虑i-1<0 的情况是因为当i = 0的时候,pos只有可能也是0, pos !=i 就已经不满足了, 不会被触发。 

posted on 2016-08-08 09:19  codingEskimo  阅读(123)  评论(0编辑  收藏  举报

导航