1. 程式人生 > >除以3, 除以1, 求最短

除以3, 除以1, 求最短

nod 描述 con lin poll() println 默認 struct root

/*
有兩個instruction,一個叫MUL,另一個叫DIV,每次用MUL的時候,就會乘以2,
每次用DIV的時候,就會除以3。初始值是1,問用最少次的instruction使得這個初始值達到target值,
這些instruction都是什麽。舉個例子來挽救一下我垃圾的描述:初始值1(默認),
target是10.先MUL,值變成2,再MUL,值變成4,再MUL,值變成8,再MUL,值變成16,再DIV,值變成5,再MUL,值變成10,
達到target,返回“MUL,MUL,MUL,MUL,DIV,MUL”。

*/
class Solution {
    class Node {
        int val;
        String path;
        public Node (int val, String path) {
            this.val = val;
            this.path = path;
        }
    }
    public void shortPath (int target) {
        Queue<Node> q = new LinkedList<>();
        Node root = new Node(1, "");

        q.add(root);
        Set<Integer> set = new HashSet<>();
        set.add(1);
        while (!q.isEmpty()) {
            Node cur = q.poll();
            if (cur.val == target) {
                System.out.println(cur.path);
                return;
            }
            if (!set.contains(cur.val * 2)) {
                Node node = new Node(cur.val * 2, cur.path + "m");
                q.offer(node);
                set.add(cur.val * 2);
            }
            if (!set.contains(cur.val / 3)) {
                Node node = new Node(cur.val / 3, cur.path + "d");
                q.offer(node);
                set.add(cur.val / 3);
            }
        }
        return;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Solution sol = new Solution();

        sol.shortPath(10);
    }
}

  

除以3, 除以1, 求最短