Japanese Yahoo programmer job-hopping program test problem

Source: Internet
Author: User
A rescue robot has three kinds of jumping mode, can jump 1m,2m,3m distance separately, please use the program to achieve the robot travel n meters of the available jumping mode.
The program language is not limited, when the distance n value is large enough, the program execution time is as small as possible.

Example: When 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 kinds of jumping mode, can jump 1m,2m,3m distance separately, please use the program to achieve the robot travel n meters of the available jumping mode.
The program language is not limited, when the distance n value is large enough, the program execution time is as small as possible.

Example: When 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 inviting me.

Out of this problem is obviously to examine you DP. I don't say much, 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,");}

When n == 4 , call: step(4, ""); output what you want.

Here is just the shortest code to express my ideas, afraid of explosion stack, self-modification.

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

To think about it briefly, the optimization idea of this topic is the same as that of the Fibonacci sequence: Record f (n).

According to the topic, F (n) =f (n-1) +f (1) =f (n-2) +f (2) =f (n-3) +f (3) =f (1) +f (n-1) =:
Two equations on the back of the phone code are not written.
F (n) may also be in these 6 species (certainly contain duplicates)

So a little deduction F (4) Because f123 is known, F4 can be obtained within O (1), recorded.
F5, at this time f1234 known, F5 can also be obtained in O (1), recorded.
then f (n), according to the above formula, can be obtained within O (n).

This is the general idea, the next solution to repeat the problem.

According to @AUV_503516 ideas, write the following code, storage structure and space can also be optimized

#!/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 as ' one ', ' + ' etc. go to the heavy     function 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, Tru e) Self._add_to_cache (3, I, True) Self._add_to_cache (1, I, False) self._add_t O_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-delt a) 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_soluti On (5)

Wrote a paragraph 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;}

Operation 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...

Well, it turned out to be a detailed list of options for each of these methods, and I didn't look seriously ... =_,=b

There will be a lot of repetitive calculations if you use recursion directly, for example, in n=7, there will be 1+1+1+steps (4), 1+2+steps (4), 3+steps (4), so step (4) will be repeated multiple times. So the result before the memory needs to be done

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, okay?

This is also the level of Oi Junior Group ... Typical dynamic programming a little bit of corner is not around.

This is also the problem of the test recursion.

If there are a total number of methods required, you can simply use an array to do dynamic planning. If you need to output all the solutions, just 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 separately to see how much the remainder is. If divisible by 3 is 3333 ...; N/3 Surplus number Y2,Y2/2 No remainder, is 33333 ... 2; N/3 more than the number of Y2,Y2/2, the final remainder is used to jump, 3333...1. The above is a large case of N. If n is less than or equal to 3, one step is sufficient.

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 of the repeated computation, the time complexity can be linearly changed into iterative or multi-point parameters in the recursive function according to the Fibonacci sequence method.

艹, the wrong question, will wrong.

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

Alas, the knowledge of C + + is completely forgotten (I can't get into Yahoo anyway). However, this topic no matter how time complexity is a number of levels, so it doesn't matter in the shortest time

Big God, you guys are all super-dicks.

  • Related Article

    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.