提交 6fe551fc 编写于 作者: L liu13

20190127

上级 897e00e4
package code;
/*
* 108. Convert Sorted Array to Binary Search Tree
* 题意:将有序数组转换为二叉平衡树
* 难度:Easy
* 分类:Tree, Depth-first Search
* 思路:类似二分查找,每次把数组劈成两半
* Tips:Bingo!
*/
public class lc108 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode tn = helper(nums, 0, nums.length-1);
return tn;
}
public TreeNode helper(int[] nums, int left, int right){
if(left<right) return null;
int mid = (left+right)/2;
TreeNode tn = new TreeNode(nums[mid]);
tn.left = helper(nums, left, mid-1);
tn.right = helper(nums, mid+1, right);
return tn;
}
}
package code;
/*
* 91. Decode Ways
* 题意:1~26代表了26个字母
* 难度:Medium
* 分类:String, Dynamic Programming
* 思路:动态规划,和上台阶问题很像
* Tips:Bingo!
*/
public class lc91 {
public static void main(String[] args) {
System.out.println(numDecodings("99"));
}
public static int numDecodings(String s) {
if(s.length()==0) return 0;
int[] dp = new int[s.length()+1];
dp[0] = 1;
int ch = s.charAt(0)-'0';
if( ch<1 || ch>9 ) return 0; //判断第一个字符是否符合规范
else dp[1] = 1;
for (int i = 2; i < s.length()+1 ; i++) {
int a = s.charAt(i-2)-'0';
int b = s.charAt(i-1)-'0';
if( (a*10+b)<=26 && (a*10+b)>=10 ) //可能存在两个字符10符合,但一个字符0不符合的情况,所以+=
dp[i] += dp[i-2];
if( b>0 && b<=9 )
dp[i] += dp[i-1];
if(dp[i]==0) return 0; //解析错误
}
return dp[s.length()];
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册