标签:
/* * 247.Strobogrammatic Number II * 2016-6-18 by Mingyang * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). * Find all strobogrammatic numbers that are of length = n. * For example, Given n = 2, return ["11","69","88","96"]. * 利用了backtracking的概念,其实就是dfs * 非常好的一道backtracking的题目,因为这里需要区分我们的奇数偶数个,所以我们需要分别来讨论 * 关键点1: * for(char c : map.keySet()) * 关键点2: * sb.insert(0, c); * sb.append(map.get(c)); * sb.deleteCharAt(0); * sb.deleteCharAt(sb.length() - 1); */ public List<String> findStrobogrammatic1(int n) { if(n < 1) return new ArrayList<String>(); List<String> res = new ArrayList<String>(); Map<Character, Character> map = new HashMap<Character, Character>(); map.put(‘0‘, ‘0‘); map.put(‘1‘, ‘1‘); map.put(‘6‘, ‘9‘); map.put(‘8‘, ‘8‘); map.put(‘9‘, ‘6‘); StringBuilder sb = new StringBuilder(); int position = (n % 2 == 0) ? 0 : 1; dfs(res, sb, map, n, position); return res; } private void dfs(List<String> res, StringBuilder sb, Map<Character, Character> map, int n, int position) { if(sb.length() > n) return; if(sb.length() == n) { res.add(sb.toString()); return; } if(position == 1) { for(char c : map.keySet()) { if(c == ‘6‘ || c == ‘9‘) continue; sb.append(c); dfs(res, sb, map, n, position + 1); sb.setLength(0); } } else { for(char c : map.keySet()) { if(n - sb.length() == 2 && c == ‘0‘) continue; sb.insert(0, c); sb.append(map.get(c)); dfs(res, sb, map, n, position + 2); sb.deleteCharAt(0); sb.deleteCharAt(sb.length() - 1); } } } //网上的改进型代码: public List<String> findStrobogrammatic(int n) { Map<Character, Character> map = new HashMap<Character, Character>(); map.put(‘0‘, ‘0‘); map.put(‘1‘, ‘1‘); map.put(‘6‘, ‘9‘); map.put(‘8‘, ‘8‘); map.put(‘9‘, ‘6‘); List<String> result = new ArrayList<String>(); char[] buffer = new char[n]; dfs(n, 0, buffer, result, map); return result; } private void dfs(int n, int index, char[] buffer, List<String> result, Map<Character, Character> map) { if (n == 0) { return; } if (index == (n + 1) / 2) { result.add(String.valueOf(buffer)); return; } for (Character c : map.keySet()) { if (index == 0 && n > 1 && c == ‘0‘) { // first digit cannot be ‘0‘ when n > 1 continue; } if (index == n / 2 && (c == ‘6‘ || c == ‘9‘)) { // mid digit cannot be ‘6‘ or ‘9‘ when n is odd continue; } buffer[index] = c; buffer[n - 1 - index] = map.get(c); dfs(n, index + 1, buffer, result, map); } }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5599450.html