算法题总结:递归

递归的三种位置表达了递归的三种用途

1.放入return中

如 return find(); 或者 return find(i) + find(j) +1; return find(i) && find(j);

1.1这种情况单纯地看成循环的优化版

这种方式等价于while循环。通过递归,把参数压入栈,优点就是比while循环中少设置了个变量,代码结构清晰。

例1:

删除链表中重复的结点

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if (pHead==NULL)
            return NULL;
        if (pHead!=NULL && pHead->next==NULL)
            return pHead;

           
        ListNode* current;
         
        if ( pHead->next->val==pHead->val){
            current=pHead->next->next;
            while (current != NULL && current->val==pHead->val)
                current=current->next;
            return deleteDuplication(current);                     
        }
         
        else {
            current=pHead->next;
            pHead->next=deleteDuplication(current);
            return pHead;
        }    
    }
}; 

1.2 利用递归计数 

return helper(i - 1, j, rows, cols, flag, threshold)
            + helper(i + 1, j, rows, cols, flag, threshold)
            + helper(i, j - 1, rows, cols, flag, threshold)
            + helper(i, j + 1, rows, cols, flag, threshold)
            + 1;

1.3 判断boolean 值

return root1.val == root2.val && trace(root1.left, root2.right) && trace(root1.right, root2.left);

2.赋值给变量

2.1  pNode.next = findnext();

这种就是利用后面返回的结果来改变变量。做个甩手掌柜。参考1.1第二个递归。

2.2 提取递归返回的值然后做判断

public class Solution {
    public int max = 0;
    int traceTree(TreeNode root, int depth){
        if(root == null) {
            return depth > max ? depth : max;
        }
        int left = traceTree(root.left,depth+1);
        int right = traceTree(root.right,depth+1);

        return left > right ? left : right; 
    }
    public int TreeDepth(TreeNode root) {
        return traceTree(root,0);
    }
}

3.放在if语句中:   

if(find(i) && find(j) && find(i+1) && find(j-1)) return true; 

或者 find(i) > 0 ? : return true: return false;

 比如:剑指offer:矩阵中的路径

猜你喜欢

转载自blog.csdn.net/raylrnd/article/details/82860068