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

前端 未结 4 1315
暖寄归人
暖寄归人 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:57

    You can try thinking about how you would solve the problem having a solution to a simpler problem. How would you solve the problem of size i if you already have a solution to the problem of size i-1, or how would you solve the problem at step i if the step i-1 and all the previous steps are already solved.

    The recursion is thinking by induction [1].

    In the case of permutations, your base case is ok, (it could also be an empty string or string with 1 element, the permutation of that string is the same string).

    But your induction step fails, try thinking that if your string is of length i, and you already have a set of all the permutations of strings of length (i-1), how would you create all the permutations of the string by having that additional i-th character?

    Now it helps to think in small cases, like 2 elements: {"ab", "ba"} What if you are given a third element "c", how do you create permutations of the string "abc" using the above elements and the solution to "ab"?

    Well the answer is: {"cab", "acb", "abc", "cba", "bca", "bac"}

    Note where "c" goes, it gets inserted at every position for each string in the previous solution. That is (pseudocode):

    res = {}
    for s in {"ab", "ba"}:
      for i = 0 to len(s):
        res.add(s.insert("c", i))
    

    Now replace {"ab", "ba"} by a recursive call with a i-1 string and you have the recursion function.

    Feel free to ask if this is not clear enough.

提交回复
热议问题