Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

78. Subsets #102

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public List<List> subsets(int[] nums) { List<List> res = new ArrayList<>(); res.add(new ArrayList()); for(int i = 0; i < nums.length; i++) { //提前取出res的size,因为res一直在改变 int size = res.size(); for(int j = 0; j < size; j++) { List temp = new ArrayList<>(res.get(j)); temp.add(nums[i]); res.add(temp); } } return res; } }

其它方法 public List<List> subsets(int[] nums) { List<List> result = new ArrayList<List>(); List list = new ArrayList(); int size = 1 << nums.length; for(int i = 0; i< size; i++){ list.clear();
for(int j = 0; j < nums.length; j++){ if((1 & (i >>> j)) == 1){ list.add(nums[j]); } } result.add(new ArrayList(list)); } return result; } 对于数组[1,2,3],可以用一个下标0和1表示是否选择该数字,0表示未选择,1表示选中,那么每一组3个0和1的组合表示一种选择,3位共有8种选择,分别是: 000 对应[] 001 对应[3] 010 对应[2] 011 对应[2,3] 100 … 101 110 111 那么上面为1的位表示数组中该位被选中。 那么只需要遍历0到1<< length中的数,判断每一个数中有那几位为1,为1的那几位即会构成一个子集中的一个元素。 http://blog.csdn.net/u012501459/article/details/46777141

Shawngbk commented 7 years ago

image