38. 字符串的排列
代码:
回溯。
class Solution {
LinkedList<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
backtrack(0);
return res.toArray(new String[0]);
}
public void backtrack(int x){
if(x == c.length - 1){
res.add(String.valueOf(c));
return;
}
HashSet<Character> set = new HashSet<>();
for(int i = x; i < c.length; ++i){
if(set.contains(c[i])){
continue;
}
set.add(c[i]);
swap(x, i);
backtrack(x+1);
swap(x,i);
}
}
public void swap(int a, int b){
char temp;
temp = c[a];
c[a] = c[b];
c[b] = temp;
}
}
17. 打印从1到最大的n位数
代码:
回溯。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
LinkedList<List<Integer>> list = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root, target);
return list;
}
public void dfs(TreeNode node, int target){
if(node == null) return;
path.add(node.val);
target -= node.val;
if(target == 0 && node.left == null && node.right == null){
list.add(new LinkedList(path));
}
dfs(node.left, target);
dfs(node.right, target);
path.pollLast();
}
}