赞
踩
function backtrack(n, used) { // 判断输入或者状态是否非法 if (input/state is invalid) { return; } // 判读递归是否应当结束,满足结束条件就返回结果 if (match condition) { return some value; } // 遍历当前所有可能出现的情况,并尝试每一种情况 for (all possible cases) { // 如果上一步尝试会影响下一步尝试,需要写入状态 used.push(case) // 递归进行下一步尝试,搜索该子树 result = backtrack(n + 1, used) // 在这种情况下已经尝试完毕,重置状态,以便于下面的回溯尝试 used.pop(case) } }
class Solution { private List<String> res = new ArrayList<>(); private final String[] letterMap = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { if (digits.length() == 0) { return res; } findCombination(digits, 0, ""); return res; } private void findCombination(String digits, int index, String s){ if(index == digits.length()){ res.add(s); return; } Character c = digits.charAt(index); String letters = letterMap[c - '0']; for(int i = 0 ; i < letters.length() ; i ++){ findCombination(digits, index+1, s + letters.charAt(i)); } return; } }
public class Solution { private List<List<Integer>> res = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { if (nums.length == 0) { return res; } boolean[] used = new boolean[nums.length]; List<Integer> list = new ArrayList<>(); backtrack(nums, 0, list, used); return res; } public void backtrack(int[] nums, int index, List<Integer> list, boolean[] used) { if (index == nums.length) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { if (!used[i]) { list.add(nums[i]); used[i] = true; backtrack(nums, index + 1, list, used); list.remove(list.size() - 1); used[i] = false; } } } }
class Solution { public List<List<String>> res = new ArrayList<>(); public List<List<String>> solveNQueens(int n) { int[] cols = new int[n]; for (int i=0; i<n; i++) { cols[i] = -1; } backtrack(0, n, cols); return res; } public void backtrack(int index, int n, int[] cols) { if (index == n) { res.add(locToList(cols)); return; } for (int i=0; i<n; i++) { cols[index] = i; if (isSafe(cols, index)) { backtrack(index+1, n, cols); } cols[index] = -1; } } public boolean isSafe(int[] cols, int index) { for (int i=0; i<index; i++) { if (cols[i] == cols[index] || i+cols[i] == index+cols[index] || i-cols[i] == index-cols[index]) { return false; } } return true; } public List<String> locToList(int[] cols) { ArrayList<String> list = new ArrayList<>(); for (int i=0; i<cols.length; i++) { StringBuilder sb = new StringBuilder(); for (int j=0; j<cols[i]; j++){ sb.append("."); } sb.append("Q"); for (int j=cols[i]+1; j<cols.length; j++){ sb.append("."); } list.add(sb.toString()); } return list; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。