> 文章列表 > 回溯递归(例题+思路+代码)

回溯递归(例题+思路+代码)

回溯递归(例题+思路+代码)

题目描述

leetcode 77

回溯递归(例题+思路+代码)

思路

组合问题适合用回溯求解。

经典解法:for循环 + 内部回溯。

每次进入回溯方法时,先判断终止条件,再进行当前层的循环,循环进行下一层递归

代码

class Solution {public List<List<Integer>> combine(int n, int k) {List<List<Integer>> result = new ArrayList<List<Integer>>();List<Integer> tempResult = new ArrayList<Integer>();dfs(result, tempResult, 1, n, k);return result;}public void dfs(List<List<Integer>> result, List<Integer> tempResult, int start, int n, int k) {if(tempResult.size() == k) {result.add(new ArrayList<Integer>(tempResult));return;}for(int i = start; i <= n; i ++) {tempResult.add(i);dfs(result, tempResult, i + 1, n, k);tempResult.remove(tempResult.size() - 1);}}
}

剪枝

由于递归本质其实就是暴力解法,所以会经过许多没有必要的节点。

该题中,如果n=4,k=3,那么在第二层中的3和4都是没有必要再经过的,所以需要剪枝。

具体只需要把for循环中判断条件改为i <= n - (k - tempResult.size()) + 1即可。

深拷贝和浅拷贝

现象:

在将List<Integer> tempResult添加进List<List<Integer>> result

如果直接add,最终每个list中结果都为空。

必须result.add(new ArrayList<Integer>(tempResult))

原因:

原因在于前者是浅拷贝,相当于把每个List<Integer> tempResult的地址值作为一个元素拷贝给List<List<Integer>> result。所以当后续修改tempResult时,结果集中的每个元素的值也会随之修改。

关于深拷贝和浅拷贝详情请看这篇博文:深拷贝和浅拷贝