[leetcode]Subsets

新博文地址:[leetcode]Subsets

Subsets

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

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

求数组s的所有子集合, Elements in a subset must be in non-descending order. 我刚开始以为默认的s也是排好序的,结果被坑了。所以在进行处理之前,需要先对s进行排序

算法思想还是DFS,跟昨天写的前几篇很像。不再啰嗦

ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> subsets(int[] s) {
    	if(s == null || s.length == 0){
    		return result;
    	}
    	Arrays.sort(s);
    	result.add(new ArrayList<Integer>());
    	for(int i = 0; i < s.length ; i++){
    		ArrayList<Integer> list = new ArrayList<Integer>();
    		dfs(i, s, list);
    	}
    	return result;
    }
    
	private void dfs(int begin,int[] s,ArrayList<Integer> list){
		if(begin < s.length){
			list.add(s[begin]);
			ArrayList<Integer> cpyList = new ArrayList<Integer>(list);
			result.add(cpyList);
		}else{
			return;
		}

		for(int i = begin + 1; i < s.length; i++){
			dfs(i,s,list);
			list.remove(list.size() - 1);//回溯
		}
	}

 

 

欢迎吐槽

 

 

你可能感兴趣的:(LeetCode)