您的位置:首页 > 其它

【LeetCode】 Subsets Subsets II

2013-10-29 15:43 429 查看
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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: