/** 247.Strobogrammatic Number II * 2016-6-18 by Mingyang * A strobogrammatic number are a number that looks The same when rotated-degrees (looked at upside). * Find All strobogrammatic numbers that is is of length = N. * For example, Given n = 2, return ["11", "69", "88", "96"]. * Using the concept of backtracking, is actually DFS * very good a backtracking topic, because here need to distinguish our odd even number, so we need to separate to discuss * key point 1: * for (char C:MAP.K Eyset ()) * Key point 2: * Sb.insert (0, C); * Sb.append (Map.get (c)); * Sb.deletecharat (0); * Sb.deletecharat (Sb.length ()-1); */ PublicList<string> FindStrobogrammatic1 (intN) {if(N < 1)return NewArraylist<string>(); List<String> res =NewArraylist<string>(); Map<character, character> map =NewHashmap<character, character>(); Map.put (' 0 ', ' 0 '); Map.put (' 1 ', ' 1 '); Map.put (' 6 ', ' 9 '); Map.put (' 8 ', ' 8 '); Map.put (' 9 ', ' 6 '); StringBuilder SB=NewStringBuilder (); intPosition = (n% 2 = = 0)? 0:1; DFS (res, SB, map, n, position); returnRes; } Private voidDFS (list<string> res, StringBuilder SB, Map<character, character> Map,intNintposition) { if(Sb.length () >N)return; if(sb.length () = =N) {res.add (sb.tostring ()); return; } if(Position = = 1) { for(CharC:map.keyset ()) { if(c = = ' 6 ' | | c = = ' 9 ') Continue; Sb.append (c); DFS (res, SB, map, n, Position+ 1); Sb.setlength (0); } } Else { for(CharC: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); } } } //improved code on-line: PublicList<string> Findstrobogrammatic (intN) {Map<character, character> map =NewHashmap<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 =NewArraylist<string>(); Char[] buffer =New Char[n]; DFS (N,0, buffer, result, map); returnresult; } Private voidDfsintNintIndexChar[] 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 is ' 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); } }
247.Strobogrammatic number II