您的位置:首页 > 其它

LeetCode - Subsets I && II

2015-03-13 01:36 465 查看
https://leetcode.com/problems/subsets/

这道题比较典型,一般需要all, every之类所有结果的,都可以用递归做,因为题目要求结果要升序,所以在做之前对数组排序,并且在做之前把空集放进去。

注意递归调用helper那行,下一个start不应该是start+1,而是i+1

public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> rst = new LinkedList<List<Integer>>();
if(S==null || S.length==0) return rst;
List<Integer> sol = new LinkedList<Integer>();
Arrays.sort(S);   // to ensure ascending order in the result list
rst.add(sol);
helper(S, 0, rst, sol);
return rst;
}
public void helper(int[] S, int start, List<List<Integer>> rst, List<Integer> sol){
for(int i=start; i<S.length; i++){
sol.add(S[i]);
rst.add(new LinkedList<Integer>(sol));
helper(S, i+1, rst, sol); //!!!should be i+1, instead of start+1 here
sol.remove(sol.size()-1);
}
}


附一个不用递归的方法:

Given a set S of n distinct integers, there is a relation between Sn and Sn-1. The subset of Sn-1 is the union of {subset of Sn-1} and {each element in Sn-1 + one more element}. Therefore,
a Java solution can be quickly formalized.

http://www.programcreek.com/2013/01/leetcode-subsets-java/

一亩三分地上对这道题时间复杂度分析:

http://www.1point3acres.com/bbs/thread-117602-1-1.html

时间复杂度分析看得不是很懂,todo:把在做完combination之后把这篇分析看懂!

Subsets II

https://leetcode.com/problems/subsets-ii/

跟Subsets I 基本完全一样,只需要在循环到下一个数时,略掉重复数就可以避免重复子集,注意,进入下一层递归时,是不需要略掉重复数的,因为一个子集里可以有重复元素。

public List<List<Integer>> subsetsWithDup(int[] S) {
List<List<Integer>> rst = new LinkedList<List<Integer>>();
if(S==null || S.length==0) return rst;
List<Integer> sol = new LinkedList<Integer>();
Arrays.sort(S);   // to ensure ascending order in the result list
rst.add(sol);
helper(S, 0, rst, sol);
return rst;
}
public void helper(int[] S, int start, List<List<Integer>> rst, List<Integer> sol){
for(int i=start; i<S.length; i++){
sol.add(S[i]);
rst.add(new LinkedList<Integer>(sol));
helper(S, i+1, rst, sol); //!!!should be i+1, instead of start+1 here
sol.remove(sol.size()-1);
while((i+1)<S.length && S[i+1]==S[i]) i++;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: