LeetCode — 22
括号组合问题:递归思想
嵌套问题:
左括号和右括号
cur.deleteCharAt(cur.length() - 1); 是为了删除cur中内容
public class test {
public static void main(String[] args) {
int n = 2;
List<String> ans = new ArrayList<String>();
backtrack(ans, new StringBuilder(), 0, 0, n);
for(String i : ans){
System.out.println(i);
}
}
public static void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append('(');
backtrack(ans, cur, open + 1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(')');
backtrack(ans, cur, open, close + 1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
LeetCode – 78. 子集
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
int i = 0;
BackTracking( i , res,list,nums);
return res;
}
public void BackTracking(int i , List<List<Integer>> res , ArrayList<Integer> list ,int[] nums){
res.add(new ArrayList<>(list));
for(int j = i ; j < nums.length; j++){
list.add(nums[j]);
BackTracking(j+1 , res , list ,nums);
list.remove(list.size()-1);
}
}
}
回溯法:
定义一个返回的数组与一个中间数组,确定循环变量,
中间数组赋值给返回数组;
for循环
- 加入数据
- 递归函数(参数加一)
- 删除数据