Verbal Arithmetic Puzzle

2020-01-02 12:09:09

问题描述:

 

问题求解

这个问题不就是小学奥数题么?都知道要暴力枚举,但是如何巧妙的枚举才是问题的关键。在打比赛的时候,我用了全排列算法,TLE了。

借鉴了别人的解法,确实实现的要优雅很多,因此在此做一个记录。

    public int[] pow_num = new int[]{1, 10, 100, 1000, 10000, 100000, 1000000};
    public boolean isSolvable(String[] words, String result) {
        Set<Character> seen = new HashSet<>();
        boolean[] isFirst = new boolean[128];
        int[] char_count = new int[128];
        for (String word : words) {
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if (!isFirst[c] && i == 0 && word.length() > 1) isFirst[c] = true;
                char_count[c] += pow_num[word.length() - i - 1];
                seen.add(c);
            }
        }
        for (int i = 0; i < result.length(); i++) {
            char c = result.charAt(i);
            if (!isFirst[c] && i == 0 && result.length() > 1) isFirst[c] = true;
            char_count[c] -= pow_num[lresult.length() - i - 1];
            seen.add(c);
        }
        char[] chs = new char[seen.size()];
        int idx = 0;
        for (char c : seen) chs[idx++] = c;
        return helper(char_count, isFirst, chs, new boolean[10], 0, 0);
    }
    
    private boolean helper(int[] char_count, boolean[] isFirst, char[] chs, boolean[] used, int step, int diff) {
        if (step == chs.length) return diff == 0;
        for (int i = 0; i < 10; i++) {
            char c = chs[step];
            if (used[i] || (i == 0 && isFirst[c])) continue;
            used[i] = true;
            if (helper(char_count, isFirst, chs, used, step + 1, diff + char_count[c] * i)) return true;
            used[i] = false;
        }
        return false;
    }

  

 

posted @ 2020-01-02 12:14  hyserendipity  阅读(377)  评论(0编辑  收藏  举报