您的位置:首页 > 其它

leetcode-78. Subsets

2017-12-06 15:27 417 查看
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]
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode