本文主要针对Backtracking类型的算法进行总结归纳解题模板。
P22. Generate Parentheses
问题描述(难度中等)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
1 | [ |
BackTracking代码
思路过程是,我们有n个左括号,n个右括号,第一次只能放一个左括号,第二次可以选择放一个右括号或者左括号。以此类推,当n>0时都可以放左括号,当m>n时都可以放右括号,最后递归的结束条件是m和n都减到零。
1 | package P22; |
P78. Subsets
问题描述(难度中等)
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
1 | Input: nums = [1,2,3] |
Backtracking解题代码
回溯法可以通过模拟树,遍历各种情况,本题可以得到下面的图,当然前提是将nums数组进行排序:
得到代码如下:
1 | package P78; |
P90. Subsets II
问题描述(难度中等)
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
1 | Input: [1,2,2] |
Backtracking回溯代码
比较第一题,主要是会出现重复的数字,重复数字出现的只需要跳过,不需要继续回溯。
1 | package P90; |
P46. Permutations
问题描述(难度中等)
Given a collection of distinct integers, return all possible permutations.
Example:
1 | Input: [1,2,3] |
BackTracking解题代码
本题break的条件有所不同,本题需要在遍历到根节点之后才记录当前数组是有效的,另外在每次的回溯过程中需要过滤已经回溯过的字段,一开始想到用Set去存储,进行重复的判断。实际上用只需要判断前缀数组是否包含即可。
1 | package P46; |