public String[] strs = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> res; public StringBuilder sb;
public List<String> letterCombinations(String digits){ res = new ArrayList<>(); if (digits.length()==0) return res; sb = new StringBuilder(); dfs(digits, 0); return res; }
publicvoiddfs(String digits, int i){ if (i==digits.length()) { res.add(sb.toString()); return; } int num = digits.charAt(i) - '0'; String str = strs[num]; for (int j=0; j<str.length(); j++) { sb.append(str.charAt(j)); dfs(digits, i+1); sb.deleteCharAt(sb.length()-1); } } }
public List<List<Integer>> res; public List<Integer> tmp; publicint[] candidates;
public List<List<Integer>> combinationSum(int[] candidates, int target) { res = new ArrayList<>(); tmp = new ArrayList<>(); Arrays.sort(candidates); this.candidates = candidates; dfs(target, 0); return res; }
publicvoiddfs(int sum, int i){ if (sum==0) { res.add(new ArrayList<>(tmp)); return; } for (int j=i; j<candidates.length; j++) { if (sum-candidates[j]<0) break;//提前剪枝 tmp.add(candidates[j]); dfs(sum-candidates[j], j); tmp.remove(tmp.size()-1); } } }
public List<List<Integer>> res; public List<Integer> tmp; publicboolean[] used; publicint[] nums;
public List<List<Integer>> permute(int[] nums) { res = new ArrayList<>(); tmp = new ArrayList<>(); used = newboolean[nums.length]; this.nums = nums; dfs(); return res; }
publicvoiddfs(){ if (tmp.size()==nums.length) { res.add(new ArrayList<>(tmp)); return; } for (int i=0; i<nums.length; i++) { if (used[i]) continue; tmp.add(nums[i]); used[i] = true; dfs(); tmp.remove(tmp.size()-1); used[i] = false; } } }
public List<List<Integer>> res; public List<Integer> tmp; publicint[] nums; publicboolean[] used;
public List<List<Integer>> subsets(int[] nums) { res = new ArrayList<>(); tmp = new ArrayList<>(); this.nums = nums; used = newboolean[nums.length]; dfs(0); return res; }
publicvoiddfs(int i){ res.add(new ArrayList<>(tmp)); if (i==nums.length) return; for (int j=i; j<nums.length; j++) { if (used[j]) continue; tmp.add(nums[j]); used[j] = true; dfs(j+1); tmp.remove(tmp.size()-1); used[j] = false; } } }
classSolution{ publicint res = 0; publicintpathSum(TreeNode root, int sum){ if (root==null) return res; preOrder(root, sum); return res; }
publicvoidpreOrder(TreeNode root, int sum){ if (root==null) return; preOrder(root.left, sum); dfs(root, sum-root.val); preOrder(root.right, sum); }
publicvoiddfs(TreeNode root, int sum){ if (sum==0) { res++; } if (root.left!=null) dfs(root.left, sum-root.left.val); if (root.right!=null) dfs(root.right, sum-root.right.val); } }