leetcode78 : 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],
  []
]
解题思路

循环加递归,这种题现在已经有了感觉。

先来个错误版的,就一个简简单单的失误。哎

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        Arrays.sort(nums);
        subsetsHelper(res, temp, 0, nums);
        return res;
    }
    private void subsetsHelper(List<List<Integer>> res, List<Integer> temp, int start, int[] nums) {
        res.add(new ArrayList<Integer>(temp));
        for (int i = start; i < nums.length; ++i) {
            temp.add(nums[i]);
            subsetsHelper(res, temp, **start** + 1, nums);
            temp.remove(temp.size() - 1);
        }
    }
}

就这一个简简单单的下标,简直有崩了狗的感觉

下面给出正确版本的

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        Arrays.sort(nums);
        subsetsHelper(res, temp, 0, nums);
        return res;
    }
    private void subsetsHelper(List<List<Integer>> res, List<Integer> temp, int start, int[] nums) {
        res.add(new ArrayList<Integer>(temp));
        for (int i = start; i < nums.length; ++i) {
            temp.add(nums[i]);
            subsetsHelper(res, temp, i + 1, nums);
            temp.remove(temp.size() - 1);
        }
    }
}

说点什么

avatar
  Subscribe  
提醒

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部