zoukankan      html  css  js  c++  java
  • 【LeetCode】 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],
      []
    ]
    

     

    Discuss

    java code :
    public class Solution {
        public ArrayList<ArrayList<Integer>> subsets(int[] S) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    		res.add(new ArrayList<Integer>());
    		if(S.length ==0)
    			return res;
    		Arrays.sort(S);
    		ArrayList<Integer> tmp = new ArrayList<Integer>();
    		for(int i = 1; i <= S.length; i++)
    		{
    			tmp.clear();
    			recursion(res,tmp,i,S,0);
    		}
    		return res;
        }
        public void recursion(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int k, int[] S, int dp)
    	{
    		if(k == tmp.size())
    		{
    			res.add(new ArrayList<Integer>(tmp));
    			return ;
    		}
    		for(int i = dp; i < S.length; i++)
    		{
    			tmp.add(S[i]);
    			recursion(res,tmp,k,S,i+1);
    			tmp.remove(tmp.size() - 1);
    		}
    	}
    }


  • 相关阅读:
    js原型杂谈
    arguments.callee.caller
    $resource
    sql的四种匹配模式
    AMD规范
    module.ngdoc
    angularjs杂谈
    浏览器前缀
    css21规范学习
    <meta>标签
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3395293.html
Copyright © 2011-2022 走看看