backtracking问题
backtracking最基础的问题是Subsets,即给定一个数组,要求返回其所有子集。
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.
backtracking的原理是深度优先遍历
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (nums == null || nums.length == 0) { return result; } Arrays.sort(nums); List<Integer> list = new ArrayList<Integer>(); subsetsHelper(nums, result, list, 0); return result; } public void subsetsHelper(int[] nums, List<List<Integer>> result, List<Integer> list, int position) { result.add(new ArrayList<Integer>(list)); for (int i = position; i < nums.length; i++) { list.add(nums[i]); subsetsHelper(nums, result, list, i + 1); list.remove(list.size() - 1); } } }
Subsets II
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.
此问题跟Subsets的不同之处在于数组中有重复元素,所以在每次for循环中需要考虑剔除掉重复元素。对subsetsHelper函数加一个判断即可。
public void subsetsHelper(int[] nums, List<List<Integer>> result, List<Integer> list, int position) { result.add(new ArrayList<Integer>(list)); for (int i = position; i < nums.length; i++) { if (i != position && nums[i] == nums[i - 1]) { continue; } list.add(nums[i]); subsetsHelper(nums, result, list, i + 1); list.remove(list.size() - 1); } }
posted on 2015-12-24 15:27 ShinningWu 阅读(171) 评论(0) 编辑 收藏 举报