标签:pos [1] 回溯 递归 开头 rem leetcode color null
该篇总结了leetcode中 78. Subsets 和 90. Subsets II,主要算法思想是DFS
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], [] ]
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> results = new ArrayList<List<Integer>>(); if (nums == null) { return results; } if (nums.length == 0) { results.add(new ArrayList<Integer>()); return results; } Arrays.sort(nums); helper(new ArrayList<Integer>(), nums, 0, results); return results; } // 递归三要素 // 1. 递归的定义:在 Nums 中找到所有以 subset 开头的的集合,并放到 results //helper函数的参数: startIndex:从哪个下标开始将元素添加进子集;results:已经添加好的子集集合;subset:上次递归形成的子集,下次递归即要找以subset开头的集合 private void helper(ArrayList<Integer> subset, int[] nums, int startIndex, List<List<Integer>> results) { // 2. 递归的拆解 // deep copy // results.add(subset); results.add(new ArrayList<Integer>(subset)); for (int i = startIndex; i < nums.length; i++) { // [1] -> [1,2] subset.add(nums[i]); // 寻找所有以 [1,2] 开头的集合,并扔到 results helper(subset, nums, i + 1, results); // [1,2] -> [1] 注意回溯 subset.remove(subset.size() - 1); } } }
90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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 class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); List<List<Integer>> results = new ArrayList<List<Integer>>(); if(nums == null){ return results; } if(nums.length == 0){ results.add(new ArrayList<Integer>()); return results; } helper(results, new ArrayList<Integer>(), nums, 0); return results; } private void helper(List<List<Integer>> results, ArrayList<Integer> list, int[] nums, int startIndex){ results.add(new ArrayList<Integer>(list)); for(int i = startIndex; i < nums.length; i++) { //与78.subsets比只增加了这一句 if(i != startIndex && nums[i] == nums[i-1]){ continue; } list.add(nums[i]); helper(results, list, nums, i+1); list.remove(list.size() - 1); } } }
标签:pos [1] 回溯 递归 开头 rem leetcode color null
原文地址:http://www.cnblogs.com/bubbleStar/p/6876159.html