2019.12.6 LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
递归方法在本题上比较高效,也很容易想到。还可以依靠动态规划的思路。
建立dp数组,dp[i]代表截至第i位字符串能够组成的地址集合。对于第i位上的地址集合,可以遍历前三位j,状态转移方程为:
dp[i] += dp[j] + num(j,i);
其中,+=表示添加,dp[j]表示集合中不大于4位的ip地址,num(j,i)表示字符串[j+1,i]范围构成的0-255的数字
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
import java.util.ArrayList;
import java.util.List;
/**
*
* Given a string containing only digits, restore it by returning all possible valid IP address combinations.
* 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
*
*/
public class RestoreIPAddresses {
//动态规划
public List<String> restoreIpAddresses(String s) {
if(s.length() > 12 || s.length() < 4){
return new ArrayList<>();
}
ArrayList<ArrayList<String>>[] dp = new ArrayList[s.length() + 1];
dp[0] = new ArrayList<ArrayList<String>>(){
{
add(new ArrayList<>());