首页 > 学院 > 开发设计 > 正文

leetcode78. Subsets

2019-11-06 07:10:06
字体:
来源:转载
供稿:网友

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

解法

采用递归的方法,直到每一个list的最后一个数为数组中最大的数,返回。 这里写图片描述

详细过程

public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> results = new ArrayList<List<Integer>>(); List<Integer> subset = new ArrayList<Integer>(); if(nums == null || nums.length == 0 ) { return results; } Arrays.sort(nums); helper(results, subset, nums, 0); return results; } PRivate void helper(List<List<Integer>> results, List<Integer> subset, int[] nums, int startIndex) { // 注意要new新的对象,不然只是对象的引用,对象发生新的变化时,results中的数会跟着变 results.add(new ArrayList<Integer>(subset)); for (; startIndex < nums.length; startIndex++) { subset.add(nums[startIndex]); helper(results, subset, nums, startIndex + 1); subset.remove(subset.size() - 1); } }}

这里写图片描述


上一篇:大数阶乘

下一篇:JDBC连接mysql入门

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表