78. 子集
Posted cznczai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了78. 子集相关的知识,希望对你有一定的参考价值。
递归
class Solution
private List ls;
private boolean []bool;
private int n;
public List<List<Integer>> subsets(int[] nums)
n = nums.length;
ls = new LinkedList<LinkedList>();
if(n==0)return ls;
bool = new boolean [n];
dfs(nums,0,bool);
return ls;
public void dfs(int nums[],int u,boolean bool[])
if(u==n)
LinkedList path = new LinkedList<LinkedList>();
for(int i = 0 ; i< n ;i++)
if(bool[i]==false)
path.add(nums[i]);
ls.add(path);
else
bool[u]= true;
dfs( nums,u+1,bool);
bool[u] = false;
dfs( nums,u+1,bool);
回溯+二进制
class Solution
private List ls;
private boolean[] bool;
private int n;
public List<List<Integer>> subsets(int[] nums)
n = nums.length;
ls = new LinkedList<LinkedList>();
bool = new boolean[n];
for (int i = 0; i < Math.pow(2, n); i++)
LinkedList path = new LinkedList<LinkedList>();
String s = Integer.toBinaryString(i);
while(s.length()!=n) s = '0'+s;
for (int x = 0; x < n; x++)
if (s.charAt(x) == '1')
path.add(nums[x]);
ls.add(path);
return ls;
以上是关于78. 子集的主要内容,如果未能解决你的问题,请参考以下文章