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