关闭

LeetCode 90 Subsets II

标签: leetcodewr
130人阅读 评论(0) 收藏 举报
分类:

Given a collection of integers that might contain duplicates, 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,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

方法一:正常迭代

	public List<List<Integer>> subsetsWithDup3(int[] nums) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		List<Integer> subSets = new ArrayList<Integer>();
		result.add(subSets);
		Arrays.sort(nums);
		int len = 0, start;
		for (int i = 0; i < nums.length; i++) {
			/**nums[i-1]已经和前面的子集并在一起作为subSets了,nums[i]==nums[i-1]就不要再做同样的事情了*/
			if (i != 0 && nums[i] != nums[i - 1]) start = 0;
			else start = len;
			len = result.size();
			for (int j = start; j < len; j++) {
				List<Integer> temp = new ArrayList<>(result.get(j));
				temp.add(nums[i]);
				result.add(temp);
			}
		}
		return result;
	}
方法二:递归

	public List<List<Integer>> subsetsWithDup(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		Arrays.sort(nums);
		getSubsetsWithDup(result, new ArrayList<Integer>(), nums, 0);
		return result;
	}

	private void getSubsetsWithDup(List<List<Integer>> result, List<Integer> list, int[] nums, int start) {
		result.add(new ArrayList<Integer>(list));
		for (int i = start; i < nums.length; i++) {
			if (i > start && nums[i] == nums[i - 1]) continue;
			list.add(nums[i]);
			getSubsets(result, list, nums, i + 1);
			list.remove(list.size() - 1);
		}
	}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27670次
    • 积分:2609
    • 等级:
    • 排名:第14479名
    • 原创:241篇
    • 转载:3篇
    • 译文:0篇
    • 评论:17条
    文章分类
    最新评论