Leetcode 分治&递归

1、Search a 2D Matrix
链接:http://oj.leetcode.com/problems/search-a-2d-matrix/

求解思路:分治法,采用分值思想,从右上开始,通过比较,可以删除改行或者该列,缩小问题规模,使得要寻找的可能区域集中在一部分。

    public boolean searchMatrix(int[][] matrix, int target){
        if(matrix.length == 0 || matrix[0].length == 0)
            return false;
        int row = matrix.length, column = matrix[0].length;
        int i = 0, j = column - 1;
        while(i < row && j >= 0){
            if(matrix[i][j] == target)
                return true;
            if(matrix[i][j] > target)
                j--;
            else i++;
        }
        return false;
    }

1、Permutations
链接:https://leetcode.com/problems/permutations/
思路一:交互数组中的两个数,递归实现

    public List<List<Integer>> permute(int[] nums) {
        int length = nums.length;
        if(length == 0)
            return null;
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < length; i++){
            list.add(nums[i]);
        }
        List<List<Integer>> result = new ArrayList<>();
        temp(list, 0, result);
        return result;
    }

    public void temp(List<Integer> list, int start, List<List<Integer>> result){
        int size = list.size();
        if(start >= size)
            result.add(new ArrayList<>(list));
        for(int i = start; i < size; i++){
            Collections.swap(list, start, i);
            temp(list, start + 1, result);
            Collections.swap(list, start, i);
        }
    }

2、Permutations II
链接:https://leetcode.com/problems/permutations-ii/
思路:与上题思路相符,交换后面没有重复的数字

    public List<List<Integer>> permuteUnique(int[] nums) {
        int length = nums.length;
        if(length == 0)
            return null;
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < length; i++){
            list.add(nums[i]);
        }
        List<List<Integer>> result = new ArrayList<>();
        permute(result, 0, list);
        return result;
    }
    private void permute(List<List<Integer>> result, int start, List<Integer> list) {
        int size = list.size();
        if(start >= size)
            result.add(new ArrayList<>(list));
        for(int i = start; i < size; i++){
            if (help(start, i, list)) continue;
            Collections.swap(list, start, i);
            permute(result, start + 1, list);
            Collections.swap(list, start, i);
        }
    }
    private boolean help(int start, int end, List<Integer> list) {
        for(int j = start; j < end; j++){
            if(list.get(j) == list.get(end))
                return true;
        }
        return false;
    }

3、Unique Binary Search Trees
链接:https://leetcode.com/problems/unique-binary-search-trees/
思路一(超时):递归思想,根为i, 则左子树为1 - i-1, 右子树 i+ 1 - n;总个数 = 左子树个数 * 右子树个数
思路二:用数组保存,总个数 = 左子树个数 * 右子树个数

    public int numTrees(int n) {
        if(n==0||n==1){
            return 1;
        }
        int sum = 0;
        for(int i=1;i<=n;i++){
            sum += numTrees(i - 1) * numTrees(n - i);
        }
        return sum;
    }
    public int numTrees(int n) {
        if(n==0||n==1){
            return 1;
        }
        int[] nums=new int[n+1];
        nums[0]=1;
        nums[1]=1;
        for(int i=2;i<=n;i++){
            int sum=0;
            for(int j=0;j<=i-1;j++){
                sum += nums[j] * nums[i-j-1];
            }
            nums[i]=sum;
        }
        return nums[n];
    }

4、Unique Binary Search Trees II
链接:https://leetcode.com/problems/unique-binary-search-trees-ii/
思路:递归方法,如上题,左右两个链表连接

    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> result = new ArrayList<>();
        if(n <= 0){
            return result;
        }
        return generateTemp(1, n);
    }
    private List<TreeNode> generateTemp(int start, int end){
        List<TreeNode> result = new ArrayList<>();
        if(start > end){
            result.add(null);
            return result;
        }
        for(int i = start; i <= end; i++){
            List<TreeNode> listLeft = generateTemp(start, i - 1);
            List<TreeNode> listRight = generateTemp(i + 1, end);
            for(TreeNode l: listLeft){
                for(TreeNode r: listRight){
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    result.add(root);
                }
            }
        }
        return result;
    }

5、Restore IP Addresses
链接:https://leetcode.com/problems/restore-ip-addresses/
思路:

6、Convert Sorted Array to Binary Search Tree
链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
思路:二分思想,中间的数为根,递归左右子树

    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length == 0)
            return null;
        return temp(nums, 0, nums.length - 1);
    }
    private TreeNode temp(int[] nums, int start, int end){
        TreeNode root = new TreeNode(-1);
        if(start > end){
            return null;
        }
        int mid = (start + end)/2;
        root.val = nums[mid];
        root.left = temp(nums, start, mid - 1);
        root.right = temp(nums, mid + 1, end);
        return root;
    }

7、Convert Sorted List to Binary Search Tree
链接:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
思路:快慢指针,找到中间节点,递归解决,注意要把链表断开,且要记录慢指针的前一个节点。

    public TreeNode sortedListToBST(ListNode head) {
        if(head == null)
            return null;
        if(head.next == null)
            return new TreeNode(head.val);
        ListNode p = head, q = head, last = head;
        while(q.next != null && q.next.next != null){
            last = p;
            p = p.next;
            q = q.next.next;
        }
        TreeNode root = new TreeNode(p.val);
        q = p.next;
        last.next = null;
        if(head != p)
            root.left = sortedListToBST(head);
        root.right = sortedListToBST(q);
        return root;
    }

8、Validate Binary Search Tree
链接:https://leetcode.com/problems/validate-binary-search-tree/
思路一:分左右子树,从根开始,调用temp,遍历全树,然后调用isValidBST, 依次判断各个节点;相当于遍历了两次
思路二:遍历一次全树,判断节点值是否在min-max之间;左枝的最大值为root值,右枝的最小值为上一个root值

public boolean isValidBST(TreeNode root) {
        if(root == null)
            return true;
        int compare = root.val;
        if(root.left != null && root.right != null){
            if(!temp(root.left, 0, compare) || !temp(root.right, 1, compare))
                return false;
            return isValidBST(root.left) && isValidBST(root.right);
        }
        if(root.left != null){
            if(!temp(root.left, 0, compare))
                return false;
            return isValidBST(root.left);
        }
        if(root.right != null){
            if(!temp(root.right, 1, compare))
                return false;
            return isValidBST(root.right);
        }
        return true;
    }
    private boolean temp(TreeNode root, int n, int compare){
        if(root == null)
            return true;
        if(n == 0){
            if(root.val >= compare)
                return false;
            return temp(root.left, 0, compare) && temp(root.right, 0, compare);
        }else{
            if(root.val <= compare)
                return false;
           return temp(root.left, 1, compare) && temp(root.right, 1, compare);
        }
    }
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean valid(TreeNode root, long low, long high) {
        if (root == null) return true;
        if (root.val <= low || root.val >= high) return false;
        return valid(root.left, low, root.val) && valid(root.right, root.val, high);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值