What is the algorithm of thinking recursive? (on the specific example)

前端 未结 4 1349
暖寄归人
暖寄归人 2021-01-13 06:23

I just can\'t wrap my head around recursion. I understand all of the concepts (breaking solution into smaller cases) and I can understand solutions after I read them over an

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 06:51

    I think recursion is the more intuitive way of solving if you get familiar with it. Simple rule is that imagine your function as a combination of the same function with smaller inputs. There are cases where recursion is more visible than others. For example permutations is one such case. Just imagine permut(S) = List{a+permut(S-{a})} for all a in S where S consists of unique characters. Idea is to select a character in string and concatenate it with all permutations of the remaining characters this will give all unique permutations of string starting with that character.

    Example pseudo code : -

    Permutation(S,List) {
    
        if(S.length>0) {
    
            for all a in S {
    
                Permutation(S.remove(a),List.add(a));
            }
    
        }
    
        else  print List;
    
     }
    

    The above code is according to me most simple to understand for permutation because it directly translates the recurrence relation where in we select a character from string and then concatenate it all other combinations of smaller string.

    Note:- This can be done more efficiently using array and swapping but it is more complex for understanding.

提交回复
热议问题