码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 078 Subsets

时间:2015-05-19 00:31:27      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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],
  []
]
解题思路:
和上十分相似,修改上题代码即可,JAVA实现如下:
    static public List<List<Integer>> subsets(int[] nums) {
    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	list.add(new ArrayList<Integer>());
    	Arrays.sort(nums);
    	for(int i=1;i<=nums.length;i++)
    		dfs(list, nums.length, i, 0,nums,-1);
    	return list;
    }

	static List<Integer> alist = new ArrayList<Integer>();

	static void dfs(List<List<Integer>> list, int n, int k, int depth,int[] nums,int last) {
		if (depth >= k) {
			list.add(new ArrayList<Integer>(alist));
			return;
		}
		for (int i = last+1; i <= n-k+depth; i++) {
			alist.add(nums[i]);
			dfs(list, n, k, depth + 1,nums,i);
			alist.remove(alist.size() - 1);
		}
	}

 

Java for LeetCode 078 Subsets

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4513237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!