leetcode-78. Subsets

来源:互联网 发布:硬盘文件恢复软件 编辑:程序博客网 时间:2024/06/02 07:01

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.

For example,
If nums = [1,2,3], a solution is:

[  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]



解法:

这题考的主要是回溯算法,对于回溯算法,我看了很多博客讲解也不是很理解。

这里找到了一位博主的讲解,是比较容易理解的:点击打开链接


对于代码的具体执行过程和如何转化的,我还是不太理解

如果有朋友看到这篇博客并且对回溯算法有比较好的理解,感谢赐教!!!!

还是附上solu:

public class Solution {      public List<List<Integer>> subsets(int[] nums) {          List<List<Integer>> res = new ArrayList<List<Integer>>();          List<Integer> temp = new ArrayList<Integer>();          dfs(res, temp, nums, 0);          return res;      }      private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int j) {          res.add(new ArrayList<Integer>(temp));          for(int i = j; i < nums.length; i++) {              temp.add(nums[i]);  //① 加入 nums[i]              dfs(res, temp, nums, i + 1);  //② 递归              temp.remove(temp.size() - 1);  //③ 移除 nums[i]          }      }  } 


原创粉丝点击