LeetCode:Restore IP Addresses

动态规划。

以前写动态规划都没用递归,发现用递归写简单不少。


package leetcode;

import java.util.ArrayList;
import java.util.Arrays;

public class RestoreIPAddresses {
	
	public static void main(String[] args) {
		RestoreIPAddresses s = new RestoreIPAddresses();
		ArrayList<String> r = s.restoreIpAddresses("172162541");
		for (String ss : r) {
			System.out.println(ss);
		}
	}
	
	private ArrayList<String>[][] result = new ArrayList[12][4];
	private boolean[][] flag = new boolean[12][4];
	private String s;
	public ArrayList<String> restoreIpAddresses(String s) {
		this.s = s;
        for (int i = 0; i < result.length; i++) {
        	for (int j = 0; j < 4; j++) {
        		if (result[i][j] != null) {
        			result[i][j].clear();
        		}
        	}
        	
        	Arrays.fill(flag[i], false);
        }
        
        if (s.length() < 4) {
        	return new ArrayList<String>();
        }
        
        return recursion(0, 4);
        
    }
	
	private ArrayList<String> recursion(int start, int count) {
		ArrayList<String> current = this.result[start][count - 1];
		if (current == null) {
			current = new ArrayList<String>();
			this.result[start][count - 1] = current;
		}
		
		if (this.flag[start][count - 1]) {
			return this.result[start][count - 1];
		}
		
		if (count == 1) {
			if (start < this.s.length() - 3) {
				this.flag[start][count-1] = true;
				return null;
			} else {
				String ss = this.s.substring(start);
				if (ss.charAt(0) != '0' || ss.length() == 1) {
					int v = Integer.valueOf(ss);
					if (v <= 255) {
						current.add(ss);
					}
				}
				
				this.flag[start][count-1] = true;
				return current;
			}
		}
		
		if (count > 1) { //剪枝
			int len = this.s.length() - start - 1;
			int minCount = len / 3;
			if (minCount > count) {
				this.flag[start][count-1] = true;
				return current;
			}
		}
		
		if (current == null) {
			current = new ArrayList<String>();
			this.result[start][count - 1] = current;
		}
		for (int i = 0; i < 3; i++) {
			String prefix = this.s.substring(start, Math.min(start + i + 1, this.s.length()));
			int v = Integer.parseInt(prefix);
			
			if (i > 0 && prefix.charAt(0) == '0') {
				continue;
			}
			
			if (v <= 255 && start + i + 1 < this.s.length()) {
				ArrayList<String> list = recursion(start + i + 1, count - 1);
				if (list != null && !list.isEmpty()) {
					for (String s : list) {
						current.add(prefix + '.' + s);
					}
				}
			}
		}
		
		this.flag[start][count - 1] = true;
		return current;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值