[LC] 78. Subsets

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

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Time: O(2^n)
Space: O(N)
class Solution:
    def subsets(self, nums: 'List[int]') -> 'List[List[int]]':
        res = []
        if nums is None or len(nums) == 0:
            return res
        self.helper(nums, 0, [], res)
        return res
            
    def helper(self, nums, index, combination, combinations):
        combinations.append(list(combination))   
        for i in range(index, len(nums)):
            combination.append(nums[i])
            self.helper(nums, i + 1, combination, combinations)
            combination.pop()
    
    
    

请问为什么需要写成list(combination), combination本身不就是list吗? 为什么把list()去掉append的就都是[]了? 

这里牵扯到一个copy问题,如果不加list,那么copy的就是combination的reference,因此list之后的改变都会导致之前加入值的改变,加上list()之后就是建立了一个当前combination的copy,之后无论list如何改变,就不变了

因为append进去的不是一个数,而是一个object(这里就是list)。之后这个object被改变了的话,之前append进去的那个list也会跟着变。比如append [1] 之后,把这个[1] 改成[2] 再append进去,得到的会是[ [2], [2] ] 而不是[ [1], [2] ]

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        helper(res, new ArrayList<>(), nums, 0);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int start) {
        res.add(new ArrayList<>(list));
     // use start to ignore the previous numbers
for (int i = start; i < nums.length; i++) { list.add(nums[i]); // use i not index b/c index smaller than i helper(res, list, nums, i + 1); list.remove(list.size() - 1); } } }
 
public class Solution {
  public List<String> subSets(String set) {
    // Write your solution here.
    List<String> res = new ArrayList<>();
    if (set == null) {
      return res;
    }
    StringBuilder sb = new StringBuilder();
    helper(res, 0, set, sb);
    return res;
  }

  private void helper(List<String> res, int index, String s, StringBuilder sb) {
    if (index == s.length()) {
      res.add(sb.toString());
      return;
    }
    helper(res, index + 1, s, sb);

    sb.append(s.charAt(index));
    helper(res, index + 1, s, sb);
    sb.deleteCharAt(sb.length() - 1);
  }
}
原文地址:https://www.cnblogs.com/xuanlu/p/11566071.html