leetcode------Subsets

标题: Subsets
通过率: 28.2%
难度: 中等

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

本题思路就是找出所有子集,具体看代码:

 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
 4         ArrayList<Integer> tmp=new ArrayList<Integer>();
 5         int[]num=S;
 6         Arrays.sort(num);
 7         dfs(res,tmp,0,num);
 8         return res;
 9     }
10     public void dfs(ArrayList<ArrayList<Integer>> res,ArrayList<Integer> tmp,int start,int[] num){
11         if(!res.contains(tmp))
12             res.add(new ArrayList<Integer>(tmp));
13         for(int i=start;i<num.length;i++){
14             tmp.add(num[i]);
15             dfs(res,tmp,i+1,num);
16             tmp.remove(tmp.size()-1);
17         }
18     }
19 }
原文地址:https://www.cnblogs.com/pkuYang/p/4341947.html