Test the job-hopping program of Yahoo programmers in Japan

Source: Internet
Author: User
A rescue robot has three skip modes, which can jump 1 m, 2 m, and 3 m respectively. Please use a program to implement the Skip mode available when the robot travels n meters. Programming languages are not limited. When the distance from n value is large enough, the program execution time should be as small as possible. For example, if the distance is 4 meters, there are 7 output results :{... A rescue robot has three skip modes, which can jump 1 m, 2 m, and 3 m respectively. Please use a program to implement the Skip mode available when the robot travels n meters.
Programming languages are not limited. When the distance from n value is large enough, the program execution time should be as small as possible.

For example, if the distance is 4 meters, there are 7 output results:

1m,1m,1m,1m1m,1m,2m1m,2m,1m1m,3m2m,1m,1m2m,2m3m,1m

Reply content:

A rescue robot has three skip modes, which can jump 1 m, 2 m, and 3 m respectively. Please use a program to implement the Skip mode available when the robot travels n meters.
Programming languages are not limited. When the distance from n value is large enough, the program execution time should be as small as possible.

For example, if the distance is 4 meters, there are 7 output results:

1m,1m,1m,1m1m,1m,2m1m,2m,1m1m,3m2m,1m,1m2m,2m3m,1m

Thank you for your invitation.

This question is clearly intended to evaluate your DP. I don't want to say much about it. I just put the code here:

cppvoid step(int n, std::string str) {    if (n == 0) { std::cout << str << "\b " << std::endl; }    if (n >= 1) step(n-1, str+"1m,");    if (n >= 2) step(n-2, str+"2m,");    if (n >= 3) step(n-3, str+"3m,");}

Whenn == 4When calling:step(4, "");Output what you want.

Here, I just use the shortest code to express my thoughts. If you are afraid of stack explosion, you can modify it on your own.

It is quite similar to my Facebook interview question: a game has 3 levels of scores: 1 point, 2 points, 5 points. please print all the ways you can get 10 points.

I briefly thought about it. The optimization idea of this question is the same as that of the Fibonacci series: record f (n ).

According to the title, f (n) = f (n-1) + f (1) = f (n-2) + f (2) = f (n-3) + f (3) = f (1) + f (n-1) = ..
The two equations behind the mobile phone code will not be written.
F (n) may be the six (of course, it must contain duplicates)

Then, a little derivation of f (4) is obtained in O (1) Because f123 is known, and F4.
F5, f1234 is known at this time, f5 can also be obtained in O (1), record.
Then f (n) can be obtained in O (n) according to the above formula.

This is the general idea. Next we can solve the repetitive problem.

According to @ AUV_503516, write the following code to optimize the storage structure and space.

#! /Usr/bin/env python3 #-*-coding: UTF-8-*-# @ file robot_steps_calculator.py # @ author kaka_ace # @ date Mar 27 2015 # @ breif # import copyclass RobotBrain (object): CACHE_INIT = {1: [['1'], 2: ['1', '1'], ['2'], 3: ['1', '1 ', '1'], ['1', '2'], ['2', '1'], ['3'],} CACHE_KEY_MAP_INIT = dict () # cache, for example, '11', '21' etc. deduplicate for k, v in CACHE_INIT.items (): for l in v: s = "". join (l) CACHE_KEY_MAP_INIT [s] = True def _ init _ (self): self. cache = copy. deepcopy (self. CACHE_INIT) self. cache_key_map = copy. deepcopy (self. CACHE_KEY_MAP_INIT) def output_solution (self, n: "total length, positive number")-> None: if n <= 3: print (RobotBrain. _ ouput_result (self. cache [n]) return I = 4 while I <= n: "" f (I) = 1 + f (I-1) = 2 + f (I-2) = 3 + f (I-3) = f (I-1) + 1 = f (I-2) + 2 = f (I-3) + 3 we need to remove duplicates "" self. cache [I] = [] for step in range (1, 4): self. _ add_to_cache (1, I, True) self. _ add_to_cache (2, I, True) self. _ add_to_cache (3, I, True) self. _ add_to_cache (1, I, False) self. _ add_to_cache (2, I, False) self. _ add_to_cache (3, I, False) I + = 1 self. _ ouput_result (self. cache [n]) def _ add_to_cache (self, delta: int, I: int, reverse: bool)-> None: for sl in self. cache [I-delta]: s = ''. join (sl) delta_str = str (delta) if reverse is True: # delta + f (I-delta) new_key = delta_str + s else: # f (I-delta) + delta new_key = s + delta_str if new_key not in self. cache_key_map: self. cache_key_map [new_key] = True self. cache [I]. append ([delta_str] + sl) @ staticmethod def _ ouput_result (cache_list)-> None: for cache_result in cache_list: print (",". join ([I + "m" for I in cache_result]) if _ name _ = "_ main _": r = RobotBrain () r. output_solution (5)

I wrote a section in C:

unsigned int count(unsigned int n){    switch(n) {        case 0: return 0;        case 1: return 1;        case 2: return 2;        case 3: return 4;        default: return (count(n - 1) + count(n - 2) + count(n - 3));    }    return 0;}

Running result:

n = 0; t = 0n = 1; t = 1n = 2; t = 2n = 3; t = 4n = 4; t = 7n = 5; t = 13n = 6; t = 24n = 7; t = 44n = 8; t = 81n = 9; t = 149...

Okay, I used to list the solutions for each method in detail. I didn't take it seriously ...... = _, = B

If recursion is used directly, there will be a lot of repeated calculations. For example, when n = 7, there will be 1 + 1 + 1 + steps (4), 1 + 2 + steps (4 ), 3 + steps (4), so step (4) is repeatedly calculated multiple times. Therefore, the results before memory is needed

int steps[LENGTH] = {0, 1, 2, 4};int n, i;for ( i = 4; i <= n; i++) {        steps[i] = steps[i-1]+steps[i-2]+steps[i-3];}printf("%d\n", steps[n]);

Write a For loop,

This is also the level of the OI middle school... typical dynamic planning is not around at all.

This is the question of recursion.

If you require a total of several methods, you can simply use an array for dynamic planning. If you want to output all the solutions, please be honest. The code is written recursively.

JAVA    /**     * return number of all distinct paths for a given distance..     * O(n) time and O(n) space using dp.     */    public int allPath(int n) {        int[] dp = new int[n+1];        dp[0] = 1; // useless        dp[1] = 1;        dp[2] = 2;        dp[3] = 4;        for (int i = 4; i <= n; i++) {            dp[i] = dp[i-1] + dp[i-2] + dp[i-3];        }        return dp[n];    }    /**     *     * return all distinct paths for a given distance.     *     */    public List
  
   > allPaths(int n) {        List
   
    > res = new ArrayList
    
     >();        helper(n, 0, new ArrayList
     
      (), res);        return res;    }    private void helper(int n, int cur, List
      
        list, List
       
        > res) { if (cur > n) { return; } if (cur == n) { res.add(list); return; } for (int i = 1; i < 4 && cur + i <= n; i++) { List
        
          newList = new ArrayList
         
          (list); newList.add(i); helper(n, cur + i, newList, res); } }
         
        
       
      
     
    
   
  

N/3, n/2, respectively, to see the remainder. If it is divided by 3, it is 3333 ...; n/3 has remainder y2, y2/2 has no remainder, that is, 33333... 2; n/3 has the remainder y2, y2/2 also has the remainder, and the final remainder uses 1 to jump, 3333... 1. N is very large. If n is less than or equal to 3, one step is enough.

F (n) = 1, n = 1
F (n) = 2, n = 2
F (n) = 4, n = 3
F (n) = f (n-1) + f (n-2) + f (n-3), n> 3

int fuck(int length){    if(length <0)    {        return 0;    }    if(length == 1 || length == 0)        return 1;    return fuck(length-1)+fuck(length-2)+fuck(length-3);}

The time complexity of the exponent. Because Repeated Computation is generated, the time complexity can be linearly changed to iteration or multi-pass parameter in the recursive function according to the Fibonacci series method.

Sorry, I have read the wrong question.

void p(const list
  
    &state){    for(auto it=state.begin();it!=state.end();it++)        if(it != --state.end())            cout<<*it<<"m,";        else            cout<<*it<<'m';    cout<
   
     append(list
    
      m,int k){    m.push_back(k);    return m;}int cfuck(int length,list
     
       state){    if(length < 0){        return 0;    }    if(length == 0) {        p(state);        return 1;    }    return cfuck(length-1,append(state,1))+cfuck(length-2,append(state,2))+cfuck(length-3,append(state,3));}
     
    
   
  

Ah, I forgot all about C ++ (I cannot enter Yahoo anyway ). However, no matter how time complexity is, this question is exponential, so it doesn't matter in the shortest time.

You are all awesome.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.