【LeetCode】 Subsets Subsets II

来源:互联网 发布:solarman软件下载 编辑:程序博客网 时间:2024/05/01 11:25

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

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

Discuss

java code :
public class Solution {    public ArrayList<ArrayList<Integer>> subsets(int[] S) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();res.add(new ArrayList<Integer>());if(S.length ==0)return res;Arrays.sort(S);ArrayList<Integer> tmp = new ArrayList<Integer>();for(int i = 1; i <= S.length; i++){tmp.clear();recursion(res,tmp,i,S,0);}return res;    }    public void recursion(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int k, int[] S, int dp){if(k == tmp.size()){res.add(new ArrayList<Integer>(tmp));return ;}for(int i = dp; i < S.length; i++){tmp.add(S[i]);recursion(res,tmp,k,S,i+1);tmp.remove(tmp.size() - 1);}}}

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],  []]

Discuss


public class Solution {    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();res.add(new ArrayList<Integer>());if(num.length ==0)return res;Arrays.sort(num);ArrayList<Integer> tmp = new ArrayList<Integer>();for(int i = 1; i <= num.length; i++){tmp.clear();recursion(res,tmp,i,num,0);}return res;    }    public void recursion(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int k, int[] S, int dp){if(k == tmp.size()){if(!res.contains(tmp))res.add(new ArrayList<Integer>(tmp));return ;}for(int i = dp; i < S.length; i++){tmp.add(S[i]);recursion(res,tmp,k,S,i+1);tmp.remove(tmp.size() - 1);}}}


原创粉丝点击