`
hcx2013
  • 浏览: 88953 次
社区版块
存档分类
最新评论

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],
  []
]

public class Solution {
	public List<List<Integer>> subsets(int[] nums) {
    	List<List<Integer>> res = new ArrayList<List<Integer>>();
    	if (nums.length<=0 || nums==null) {
    		return res;
    	}
    	Arrays.sort(nums);
    	ArrayList<Integer> list = new ArrayList<Integer>();
    	for (int i = 1; i <= nums.length; i++) {
    		dfs(nums, 0, i, list, res);
    	}
    	res.add(new ArrayList<Integer>());
    	return res;
    }

	private void dfs(int[] arr, int start, int len, ArrayList<Integer> list,
			List<List<Integer>> res) {
		if (list.size() == len) {
			res.add(new ArrayList<Integer>(list));
			return;
		}
		for (int i = start; i < arr.length; i++) {
			list.add(arr[i]);
			dfs(arr, i+1, len, list, res);
			list.remove(list.size()-1);
		}
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics