14ms Java Backtracking


  • 0

    public class Solution {
    char[] key = {'0', '1', '6','8','9'};
    char[] val = {'0', '1', '9','8','6'};
    List<String> res = new ArrayList<String>();
    public List<String> findStrobogrammatic(int n) {
    StringBuilder sb = new StringBuilder();
    if((n&1) == 0){
    buildString(sb,n);
    }
    else{
    for(int i = 0; i < key.length; i++){
    if(key[i] != '6' && key[i] != '9'){
    sb.append(key[i]);
    buildString(sb, n-1);
    sb.deleteCharAt(0);
    }
    }

        }        
        return res;
    }
    
    public void buildString(StringBuilder sb, int n){
        if(n == 0){
            if((sb.length() == 1 && sb.charAt(0) == '0') ||sb.charAt(0)!= '0'){
                res.add(sb.toString());    
            }
            return;
        }
        for(int i = 0; i < key.length; i++){
            sb.insert(0,key[i]);
            sb.append(val[i]);
            buildString(sb, n-2);
            sb.deleteCharAt(0);
            sb.deleteCharAt(sb.length()-1);
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.