2015年10月29日星期四

Strobogrammatic Number II leetcode

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"].
Arrays.asList() -->返回一个包含括号内元素的arraylist
第一种方法 从中间向两边插入
public class Solution {
    public List<String> findStrobogrammatic(int n) {
        return helper(n, n);
    }
    public List<String> helper(int m, int n) {
        if (m == 1) {
            List<String> res = Arrays.asList("0", "1", "8");
            return res;
        }
        if (m == 0) {
            List<String> res = Arrays.asList("");
            return res;
        }
        List<String> list = helper(m - 2, n);
        List<String> res = new ArrayList<String>();
        for (String s : list) {
            if (n != m) {
                res.add("0" + s + "0");
            }
            res.add("1" + s + "1");
            res.add("6" + s + "9");
            res.add("8" + s + "8");
            res.add("9" + s + "6");
        }
        return res;
    }
}


第二种方法 两边往中间插

public class Solution {
    char[] list = {'0', '1', '8', '6', '9'};
    public List<String> findStrobogrammatic(int n) {
        
        List<String> res = new ArrayList<String>();
        helper(new char[n], res, 0, n - 1);
        return res;
    }
    public void helper(char [] cur, List<String> res, int left, int right) {
        if (left > right) {
            res.add(new String(cur));
            return;
        }else if (left == right) {
            for (int i = 0; i < 3; i++) {
                cur[left] = list[i];
                res.add(new String(cur));
            }
            return;
        } else {
            int i = 0;
            if (left == 0) {
                i = 1;
            }
            for (; i < 5; i++) {
                if (i < 3) {
                    cur[left] = list[i];
                    cur[right] = list[i];
                } else if (i == 3) {
                    cur[left] = '6';
                    cur[right] = '9';
                } else {
                    cur[left] = '9';
                    cur[right] = '6';
                }
                helper(cur, res, left + 1, right - 1);
            }
        }
            
        
    }
}

没有评论:

发表评论