回溯法有模板:
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)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
- leetCode 46 全排列
給定一個 沒有重複 數字的序列,返回其所有可能的全排列。
示例:
輸入: [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<List<Integer>> permute(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
backtrack(nums, path, res);
return res;
}
private void backtrack( int[] nums, LinkedList<Integer> path, List<List<Integer>> 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(); //撤銷選擇
}
}
}
- 77 組合(meduim)
給定兩個整數 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<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
Deque<Integer> path = new ArrayDeque<Integer>();
backtrack(n, k, 1, path);
return res;
}
private void backtrack(int n, int k, int begin, Deque<Integer> 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();
}
}
}