Verbal Arithmetic Puzzle

2020-01-02 12:09:09

Problem Description:

 

Problem Solving :

The problem is not that primary school Olympiad title it? To enumerate all know that violence, but how clever enumeration is the key issue. In the play, I spent the whole ranking algorithm, TLE up.

Learn from someone else's solution, to really achieve a lot of elegance, so in this to make a record.

    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;
    }

  

 

Guess you like

Origin www.cnblogs.com/hyserendipity/p/12132264.html