91. 解码方法
动态规划,爬楼梯
public static int numDecodings(String s) {
int n = s.length();
s = " " + s;
char[] cs = s.toCharArray();
int[] f = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
int a = cs[i] - '0', b = (cs[i - 1] - '0') * 10 + (cs[i] - '0');
if (1 <= a && a <= 9) f[i] = f[i - 1];
if (10 <= b && b <= 26) f[i] += f[i - 2];
}
return f[n];
}
92.反转链表2
头插法
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode node=new ListNode();
node.next=head;
ListNode i=node;
ListNode j=node.next;
for (int step = 0; step < left-1; step++) {
i=i.next;
j=j.next;
}
for (int k = 0; k < right-left; k++) {
ListNode nextNode=j.next;
j.next=j.next.next;
nextNode.next=i.next;
i.next=nextNode;
}
return node.next;
}
93.复原IP地址
List<String> result = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12) return result;
backTrack(s, 0, 0);
return result;
}
private void backTrack(String s, int startIndex, int pointNum) {
if (pointNum == 3) {
if (isValid(s,startIndex,s.length()-1)) {
result.add(s);
}
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isValid(s, startIndex, i)) {
s = s.substring(0, i + 1) + "." + s.substring(i + 1);
pointNum++;
backTrack(s, i + 2, pointNum);
pointNum--;
s = s.substring(0, i + 1) + s.substring(i + 2);
} else {
break;
}
}
}
private Boolean isValid(String s, int start, int end) {
if (start > end) {
return false;
}
if (s.charAt(start) == '0' && start != end) {
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
if (s.charAt(i) > '9' || s.charAt(i) < '0') {
return false;
}
num = num * 10 + (s.charAt(i) - '0');
if (num > 255) {
return false;
}
}
return true;
}
95.不同的二叉搜索树
太抽象了,如果换成别的可能好想,树结构这么看抽象了
public List<TreeNode> generateTrees(int n) {
return generateTrees(1, n);
}
private List<TreeNode> generateTrees(int start, int end) {
List<TreeNode> curRes = new LinkedList<>();
if (start > end) {
curRes.add(null);
return curRes;
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftNodeList = generateTrees(start, i - 1);
List<TreeNode> rightNodeList = generateTrees(i + 1, end);
for (TreeNode leftNode : leftNodeList) {
for (TreeNode rightNode : rightNodeList) {
curRes.add(new TreeNode(i, leftNode, rightNode));
}
}
}
return curRes;
}
96.不同的二叉搜索树
public int numTrees(int n) {
if (n <= 2) return n;
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
|