标签:是什么 out 例子 contains integer arp contain this pre
/*
有两个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); } }
标签:是什么 out 例子 contains integer arp contain this pre
原文地址:http://www.cnblogs.com/apanda009/p/7858989.html