LeetCode_OJ【78】Subsets

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Subscribe to see which companies asked this question

返回一个集合的所有子集,子集中所有元素按顺序排列。

这个题第一反应就是用回溯,思路比较常规,性能也不错,这里就不介绍了,下面是JAVA实现:

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		List<Integer> path = new ArrayList<Integer>();
		List<Integer> rem = new ArrayList<Integer>();
		for(int i = 0 ; i < nums.length ; i++)
			rem.add(nums[i]);
		Collections.sort(rem);
		generate(res,path,rem,0);
		return res;
    }
	
	public void generate(List<List<Integer>> res,List<Integer> path,List<Integer> rem, int k){
		res.add(new ArrayList<Integer>(path));
		if(k == rem.size())
			return;
		for(int i = k ; i < rem.size() ; i ++){
			path.add(rem.get(i));
			rem.remove(i);
			generate(res,path,rem,i);
			Integer last = path.remove(path.size() -1);
			rem.add(i,last);
		}
	}
}

后来看到提示里面有 位操作,以前从来没碰到这种解法的题目,找了一些资料看了下,还是很受启发的。

nums里面有n个元素,那么有2^n个子集,用数字0 ~ (2^n-1) 分别表示这些子集,对于任意一个数字,如果其对应的2进制数中的第 i 位为1,则表示nums[i]包含在该数字对应的子集中。

这样可以直接通过循环一个一个将子集计算出来,效率比回溯要高一些。

下面是位操作的JAVA实现:

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		int max = 1 << nums.length;
		Arrays.sort(nums);
		for( ; max > 0 ; max --){
			List<Integer> tmp = new ArrayList<Integer>();
			for(int i = max -1,index = 0 ; i > 0 ; i = i >> 1,index ++){
				if((i & 1) == 1)
					tmp.add(nums[index]);
			}
			res.add(tmp);
		}
		return res;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值