LeetCode:Subsets I
来源:互联网 发布:hp m1216nfh 网络扫描 编辑:程序博客网 时间:2024/05/16 14:42
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], []]
开始想法以给定数组为字典序进行排序,给定一个子序列之后求下一个序列,最终得到全部序列:
public class Solution { ArrayList<Integer> nextSubSet(ArrayList<Integer> in,int [] A) { int len=A.length; int i,j,size=in.size(); if(len==size)return null; int num=in.get(0); ArrayList<Integer> out=new ArrayList<Integer>(); if(num==A[len-size]){ for(i=0;i<size+1;i++)out.add(A[i]); return out; } Iterator<Integer> it=in.iterator(); while(it.hasNext())out.add(it.next()); i=0; while(out.get(size-1-i)==A[len-1-i])i++; i=size-1-i; num=out.get(i); for(j=0;j<len;j++)if(A[j]==num)break; out.set(i,A[j+1]); i=i+1; j=j+2;for(;i<size;i++,j++)out.set(i,A[j]); return out; } public ArrayList<ArrayList<Integer>> subsets(int[] S) { ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>(); int len=S.length; if(len==0)return list; Arrays.sort(S); ArrayList<Integer> innerList=new ArrayList<Integer>(); list.add(innerList); innerList=new ArrayList<Integer>(); innerList.add(S[0]); while(innerList!=null) { list.add(innerList); innerList=nextSubSet(innerList,S); } return list; }}
之后想到可以用递归直接来做,实质上是DFS:
public class Solution { ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> copy(ArrayList<Integer> in) { ArrayList<Integer> out=new ArrayList<Integer>(); Iterator<Integer> it=in.iterator(); while(it.hasNext())out.add(it.next()); return out; } public void dfs(int [] A,int index,ArrayList<Integer> in) { if(index==A.length){ ArrayList<Integer> out=copy(in); list.add(out); return; } in.add(A[index]); dfs(A,index+1,in); in.remove(in.size()-1); dfs(A,index+1,in); } public ArrayList<ArrayList<Integer>> subsets(int[] S) { ArrayList<Integer> in=new ArrayList<Integer>(); int len=S.length; Arrays.sort(S); dfs(S,0,in); return list; }}
0 0
- 【LeetCode】Subsets I && II
- LeetCode:Subsets I
- [Leetcode]Subsets I&II
- LeetCode - Subsets I && II
- LeetCode | Subsets I,II
- LeetCode:Subsets I II
- leetcode -day31 Subsets I II
- LeetCode题解:Subsets I and II
- <LeetCode OJ> 78 / 90 Subsets (I / II)
- LeetCode 78, 90. Subsets i, ii
- [Leetcode] #78#90 Subsets I & II
- Subsets I
- 【LeetCode】 Subsets Subsets II
- 【LeetCode】Subsets & Subsets II
- LeetCode Subsets && Subsets II
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- [leetcode 78 & 90, Medium] Subsets I and II
- 如何为运行在SAP的SQL Server计划性能
- js 右键菜单、禁止剪切、复制、粘贴的文本框代码
- 实现数组反转
- 在 Visual C++ 中以错误的顺序链接 CRT 库和 MFC 库时出现 LNK2005 错误
- 数字证书的原理
- LeetCode:Subsets I
- .NET中的范型
- delete from和truncate table的区别
- Parencodings
- listview分页加载问题
- as3 各显示对象的层级关系
- WS-* 协议
- sqlmap使用post方法对cookie进行注入
- Linux批量替换多个文件中字符串