回溯法有模板:
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
returnfor 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择作者:jeromememory
链接:https://leetcode-cn.com/problems/combination-sum/solution/hui-su-suan-fa-tao-mo-ban-ji-ke-by-jeromememory/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
解题模板思路:
按照前面的模板解题,但是需要注意:
- 路径的撤销选择需要满足最先添加最后撤销(FILO),所以要是用队列数据结构,分别用add(元素)、removeLast()方法;
- 需要剪枝:对包含自身的子路径,不应该执行。
代码:
public class Solution {
public List> permute(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List> res = new ArrayList<>();
LinkedList path = new LinkedList<>();
backtrack(nums, path, res);
return res;
}
private void backtrack( int[] nums, LinkedList path, List> res) {
if (path.size() == nums.length) { //满足条件则添加结果
res.add(new LinkedList(path));
}
for (int i = 0 ; i < nums.length ; i++ ) { //选择列表
if (path.contains(nums[i])) {
continue; //剪枝
}
path.add(nums[i]); //添加选择
backtrack(nums, path, res); //回溯
path.removeLast(); //撤销选择
}
}
}
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
class Solution {
List> res = new ArrayList<>();
public List> combine(int n, int k) {
Deque path = new ArrayDeque();
backtrack(n, k, 1, path);
return res;
}
private void backtrack(int n, int k, int begin, Deque path) {
if (path.size() == k) {
res.add(new ArrayList(path));
return;
}
for (int i = begin; i <= n; i++) {
path.addLast(i);
backtrack(n, k, i + 1, path);
path.removeLast();
}
}
}