LC.78. + LF.62. SubsetsI

Given a set of distinct integers, nums, return all possible subsets (the power set).

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

 

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>() ; 
        if(nums == null ){
            return res ; 
        }
        List<Integer> sol = new ArrayList<>(); 
        helper(nums, res, 0, sol) ; 
        return res ; 
    }
    private void helper(int[] nums, List<List<Integer>> res , int index, List<Integer> sol){
        //termination point: note sol here is reference type so make a deep copy
        if(index == nums.length ){
            res.add(new ArrayList<>(sol)); 
            return ; 
        }
        //case 1: add
        sol.add(nums[index]) ;
        helper(nums, res, index+1 , sol) ;
        sol.remove(sol.size()-1);
        //case 2: dont add
        helper(nums, res, index+1 , sol) ;
    }
}

time:  o(2^n) elements 

space: o(n)  # of calling stacks

 

LF.62:

Given a set of characters represented by a String, return a list containing all subsets of the characters.

Assumptions

There are no duplicate characters in the original set.
​Examples

Set = "abc", all the subsets are [“”, “a”, “ab”, “abc”, “ac”, “b”, “bc”, “c”]
Set = "", all the subsets are [""]
Set = null, all the subsets are []

 

 1 public class Solution {
 2   public List<String> subSets(String set) {
 3     // Write your solution here.
 4     List<String> res = new ArrayList<>() ;
 5     if (set == null) {
 6         return res ;
 7     }
 8     char[] arraySet = set.toCharArray() ;
 9     StringBuilder sol = new StringBuilder() ;
10     helper(arraySet,res, 0 , sol);
11     return res ;
12   }
13   /*
14     index: 控制第几层
15   */
16   private void helper(char[] set, List<String> res, int index, StringBuilder sol ){
17     /*terminate condition:
18     when we finishes determining for all the chars pick or not,
19     we have a complete subset.
20     */
21     if (index == set.length) {
22         res.add(sol.toString()) ;
23         return ;
24     }
25     //case 1: pick the character at index
26     helper(set,res,index+1,sol.append(set[index]));
27     //remember to remove the added character when back tracking to //the previous level
28     sol.deleteCharAt(sol.length()-1) ;
29     //case 2: not pick the character at index
30     helper(set,res,index+1, sol);
31   }
32 }

 

 

 

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8688770.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值