LeetCode 78. Subsets 解题报告

78. Subsets

My Submissions
Question
Total Accepted: 84229  Total Submissions: 276420  Difficulty: Medium

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    这道题要求一个集合的所有子集。如果一个集合有n个元素,那么会有2的n次方个子集。用深搜求解。

    我的AC代码

public class Subsets {

	public static void main(String[] args) {
		int[] a = { 1, 2, 3 };
		System.out.println(subsets(a));
	}

	public static List> subsets(int[] nums) {
		List> ll = new ArrayList>();
		Arrays.sort(nums);
		dfs(nums, new ArrayList(), 0, ll);
		return ll;
	}

	private static void dfs(int[] nums, ArrayList l, int i, List> ll) {
		if (i == nums.length) {
			ll.add((List) l.clone());
			return;
		}
		l.add(nums[i]);
		dfs(nums, l, i + 1, ll);
		l.remove(l.size() - 1);
		dfs(nums, l, i + 1, ll);
	}
}


你可能感兴趣的:(LeetCodeOJ,LeetCode,OJ,解题报告)