78. Subsets

Given a set of distinct integers, nums, return all possible subsets.

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

含义:给一个没有重复数字的字符串,获取所有的子串(子串中不能有重复数字)
方法一:BFS
 1     public List<List<Integer>> subsets(int[] nums) {
 2 //        The idea is:
 3 //        起始subset集为:[]
 4 //        添加S0后为:[], [S0]
 5 //        添加S1后为:[], [S0], [S1], [S0, S1]
 6 //        添加S2后为:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2]
 7 //        红色subset为每次新增的。显然规律为添加Si后,新增的subset为克隆现有的所有subset,并在它们后面都加上Si。
 8 
 9         List<List<Integer>> result = new ArrayList<List<Integer>>();
10         List<Integer> tmp = new ArrayList<Integer>();
11         result.add(tmp); // add empty set
12         Arrays.sort(nums);
13         for (int i=0;i<nums.length;i++)
14         {
15             int n = result.size();
16             for (int j=0;j<n;j++)
17             {
18                 tmp = new ArrayList<Integer>(result.get(j));
19                 tmp.add(nums[i]);
20                 result.add(new ArrayList<Integer>(tmp));
21             }
22         }
23         return result;        
24     }

 方法二:回溯算法|递归实现

本解法采用回溯算法实现,回溯算法的基本形式是“递归+循环”,正因为循环中嵌套着递归,递归中包含循环,这才使得回溯比一般的递归和单纯的循环更难理解,其实我们熟悉了它的基本形式,就会觉得这样的算法难度也不是很大。原数组中的每个元素有两种状态:存在和不存在。

① 外层循环逐一往中间集合 temp 中加入元素 nums[i],使这个元素处于存在状态

② 开始递归,递归中携带加入新元素的 temp,并且下一次循环的起始是 i 元素的下一个,因而递归中更新 i 值为 i + 1

③ 将这个从中间集合 temp 中移除,使该元素处于不存在状态

 1 public class Solution {  
 2     public List<List<Integer>> subsets(int[] nums) {  
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();  
 4         List<Integer> temp = new ArrayList<Integer>();  
 5         dfs(res, temp, nums, 0);  
 6         return res;  
 7     }  
 8     private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int j) {  
 9         res.add(new ArrayList<Integer>(temp));  
10         for(int i = j; i < nums.length; i++) {  
11             temp.add(nums[i]);  //① 加入 nums[i]  
12             dfs(res, temp, nums, i + 1);  //② 递归  
13             temp.remove(temp.size() - 1);  //③ 移除 nums[i]  
14         }  
15     }  
16 }  
原文地址:https://www.cnblogs.com/wzj4858/p/7676108.html