注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
请问为什么本题在递归调用必须要用helper(res, new ArrayList<>(each), i + 1, n), 用helper(res, each , i + 1, n)就会出现下面的错误呢?在debug打印时,each还是正确的,为什么在result结果中所有的each都变成了空?谢谢大神们解答,会尽力给大家加米(一天只能加10粒米,一次只能加一粒,谢谢大家)。
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],
[]
]
- public class Solution {
- public List<List<Integer>> subsets(int[] nums) {
- Arrays.sort(nums);
- List<List<Integer>> res = new ArrayList<>();
- List<Integer> each = new ArrayList<>();
- helper(res, each, 0, nums);
- return res;
- }
- public void helper(List<List<Integer>> res, List<Integer> each, int pos, int[] n) {
- //为了debug,打印一些parameter
- System.out.print(" This is sub-list need to be added ");
- System.out.print(each);
- System.out.print(" pos: ");
- System.out.print(pos);
- System.out.println(" ");
- //debug结束
- if (pos <= n.length) {
- res.add(each);
- }
- for (int i = pos; i < n.length; i++) {
- each.add(n[i]);
- helper(res,each, i + 1, n);
- each.remove(each.size() - 1);
- }
- return;
- }
- }
复制代码
------------------这是结果和debug打印结果-----------------------
Your input
[1,2,3]
stdout
This is sub-list need to be added [] pos: 0
This is sub-list need to be added [1] pos: 1
This is sub-list need to be added [1, 2] pos: 2
This is sub-list need to be added [1, 2, 3] pos: 3
This is sub-list need to be added [1, 3] pos: 3
This is sub-list need to be added [2] pos: 2
This is sub-list need to be added [2, 3] pos: 3
This is sub-list need to be added [3] pos: 3
Output
[[],[],[],[],[],[],[],[]]
Expected
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
|