您的位置:首页 > 其它

[leetcode]Subsets

2014-07-25 22:40 369 查看

Subsets


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


算法思路:

题中要求求出所有的,直接暴力吧,dfs

代码如下:

public class Solution {  List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] s) {
if(s == null || s.length== 0) return res;
Arrays.sort(s);
List<Integer> list = new ArrayList<Integer>();
dfs(list,0,0,s);
return res;
}
private void dfs(List<Integer> list,int k,int count,int[] s){
if(count > s.length) return;
if(count <= s.length){
res.add(new ArrayList<Integer>(list));
}
for(int i = k; i < s.length; i++){
list.add(s[i]);
dfs(list,i + 1,count+1,s);
list.remove(list.size() - 1);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: