LeetCode 078 Subsets

来源:互联网 发布:淘宝卖家中心下载 编辑:程序博客网 时间:2024/05/26 22:10
题目


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 典型的DFS+回溯
2 注意题目要求不能递减,所以递归前先排序不要忘记
3 按照坐标的增长来递归即可。

代码


public class Solution {    public ArrayList<ArrayList<Integer>> subsets(int[] S) {        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();        ArrayList<Integer> temp = new ArrayList<Integer>();        Arrays.sort(S);        ans.add(temp);        useme(ans,temp,0,S);        return ans;    }        public void useme(ArrayList<ArrayList<Integer>> ans,ArrayList<Integer> temp,int start,int[] S){        for(int i=start;i<S.length;i++){            temp.add(S[i]);            ans.add(new ArrayList<Integer>(temp));            useme(ans,temp,i+1,S);            temp.remove(temp.size()-1);        }    }}




0 0