显示标签为“dfs”的博文。显示所有博文
显示标签为“dfs”的博文。显示所有博文

2015年10月21日星期三

Combination Sum III leetcode

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.

Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]

Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (k <= 0) {
            return res;
        }
        List<Integer> tem = new ArrayList<Integer>();
        helper(res, tem, k, n, 1, 0, 0);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> tem, int k, int n, int pos, int sum, int count) {
        if (sum == n && count == k) {
            res.add(new ArrayList<Integer>(tem));
            return;
        }

        for (int i = pos; i <= 9; i++) {
            tem.add(i);
            helper(res, tem, k, n, i + 1, sum + i, count+1);
            tem.remove(tem.size() - 1);
        }
    }
}

2015年6月22日星期一

Unique Binary Search Trees II leetcode

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example, Given n = 3, your program should return all 5 unique BST's shown below.
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
引用code ganker(http://codeganker.blogspot.com/2014/04/unique-binary-search-trees-ii-leetcode.html)的讲解:
”这道题是求解所有可行的二叉查找树,从Unique Binary Search Trees中我们已经知道,可行的二叉查找树的数量是相应的卡特兰数,不是一个多项式时间的数量级,所以我们要求解所有的树,自然是不能多项式时间内完成的了。算法上还是用求解NP问题的方法来求解,也就是N-Queens中 介绍的在循环中调用递归函数求解子问题。思路是每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取 然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况),构造好之后作为当前树的 结果返回。 “
public class Solution {
    public ArrayList<TreeNode> generateTrees(int n) {
        return helper(1, n);
    }
    public ArrayList<TreeNode> helper(int left, int right) {
        ArrayList<TreeNode> res = new ArrayList<TreeNode>();
        if (left > right) {
            res.add(null);
            return res;//最终的res才返回helper函数 中间的都返回到leftlist或者rightlist中去
        }
        for (int i = left; i<= right; i++) {//取left到right间每个节点作为根
            ArrayList<TreeNode> leftlist = helper(left, i -1);//以i作为根节点,左子树由[1,i-1]构成
            ArrayList<TreeNode> rightlist = helper(i + 1, right);//右子树由[i+1, n]构成
            for (int j = 0; j < leftlist.size(); j++) {
                for (int k = 0; k < rightlist.size(); k++) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftlist.get(j);
                    //对于任何j,leftlist[j]都是由0~ i-1构成的不同形式的左子树
                    root.right = rightlist.get(k);
                    res.add(root);
                }
            }
        }
        return res;
    }
}

2015年6月9日星期二

Sum Root to Leaf Numbers leetcode

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
用递归的方法来做, 把根节点到叶子节点所有值加起来, 递归条件是把当前的sum*10 加上子节点的值进行下一轮递归
结束条件是到子节点是空的时候就返回0
算法的本质是一次先序遍历,所以时间是O(n),空间是栈大小,O(logn)。

public class Solution {
    public int sumNumbers(TreeNode root) {
        return helper(root, 0);    
    }
    public int helper(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return sum * 10 + root.val;
        }
        int left = helper(root.left, sum*10 + root.val);
        int right = helper(root.right, sum*10 + root.val);
        return left + right;
    }
}

Path Sum II leetcode

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]
一般求结果的都用递归求解 这里的时间复杂度仍然只是一次遍历O(n),而空间复杂度则取决于满足条件的路径和的数量(假设是k条),则空间是O(klogn)。

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> tem = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        tem.add(root.val);
        helper(root, sum, res, tem);
        return res;
    }
    public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer>tem) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null & sum == root.val) {
            res.add(new ArrayList<Integer>(tem));
            return;
        }
        if (root.left != null) {
            tem.add(root.left.val);
            helper(root.left, sum - root.val, res, tem);
            tem.remove(tem.size() - 1);
        }
        if (root.right != null) {
            tem.add(root.right.val);
            helper(root.right, sum - root.val, res, tem);
            tem.remove(tem.size() - 1);
        }
        
    }
}