leetcode 93. Restore IP Addresses
2016-04-26 22:24
429 查看
发现我不会上图啊。。。这样我就不加题目描述了。反正题目已经写清题号了,你们去leetcode按图索驹就是了。就是个典型的回溯法,主要麻烦在各种情况的处理上了。话说回溯法和字符串处理结合的题套路还满固定,要诀主要在递归函数的设计,设计的不合理了就会很麻烦。我恰每次都要忙活半天。。还是要练啊。下面是代码:
public class Solution { List<String> out=null; public List<String> restoreIpAddresses(String s) { out=new ArrayList<String>(); if(s.length()<4)return out; String str=""; help(s,0,str,1); return out; } void help(String s,int head,String str,int count){ for(int i=head+1;i<=Math.min(head+3,s.length()+1);i++){ int num=Integer.parseInt(s.substring(head,i)); if(s.charAt(head)=='0'&&num!=0)return;//0.03.illegal if(num==0&&i-head>1)return;//0.00.illegal if(num<256){ String o=str+num; if(count==4){ if(i!=s.length())continue;//0.0.0.0 0illegal out.add(o); return; }else { o+="."; if(s.length()-i<4-count)return; help(s,i,o,count+1); } } } } }
相关文章推荐
- C#使用回溯法解决背包问题实例分析
- javascript递归回溯法解八皇后问题
- java使用回溯法求解数独示例
- 算法详解之回溯法具体实现
- PHP回溯法解决0-1背包问题实例分析
- C++回溯法实例分析
- python回溯法实现数组全排列输出实例分析
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem