1. 程式人生 > >【BFS】【遞推】【Java】位元組跳動2018.3筆試T2

【BFS】【遞推】【Java】位元組跳動2018.3筆試T2

定義兩個字串變數:sm,再定義兩種操作, 
  
第一種操作:

m = s
s = s + s
第二種操作:

s = s + m
  
假設sm初始化如下:

s = "a"
m = s
求最小的操作步驟數,可以將s拼接到長度等於n

class Nodes{
    int s;
    int m;
    public Nodes(){

    }
    public Nodes(int s,int m){
        this.s=s;
        this.m=m;
    }
}
public class BFS {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        Nodes nodes=new Nodes(1,1);
        Map<Nodes,Integer> map=new HashMap<Nodes,Integer>();
        map.put(nodes,0);
        Queue<Nodes> queue=new LinkedList();
        queue.add(nodes);
        while (!queue.isEmpty()){
            Nodes nodes1=queue.poll();
            if (nodes1.s==n){
                System.out.println(map.get(nodes1));
                break;
            }
            Nodes left=new Nodes();
            left.m=nodes1.s;
            left.s=nodes1.s*2;
            map.put(left,map.get(nodes1)+1);
            queue.add(left);
            
            Nodes right=new Nodes();
            right.s=nodes1.s+nodes1.m;
            right.m=nodes1.m;
            map.put(right,map.get(nodes1)+1);
            queue.add(right);
        }

    }
}