小编Mor*_*rty的帖子

为什么“res.add(new ArrayList<>(list));” 这里?

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

我正在研究Leetcode 113. Path Sum II。这与问题本身无关。我想知道为什么我必须写 …

java

3
推荐指数
1
解决办法
1776
查看次数

这里 k - 1 和 --k 的区别,实在不明白

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        List<Integer> cur = new ArrayList<>();
        helper(res, cur, n, k, 1);
        return res;
    }
    private void helper (List<List<Integer>> res, List<Integer> cur, int n, int k, int start) {
        if (k == 0) {
            res.add(new ArrayList<>(cur));
            return;
        }
        for (int i = start; i <= n; i++) {
            cur.add(i);
            helper(res, cur, n, k - 1, i + 1); // …
Run Code Online (Sandbox Code Playgroud)

java

1
推荐指数
1
解决办法
238
查看次数

Python:为什么附加到列表会产生相同的值

这是我的代码:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
Run Code Online (Sandbox Code Playgroud)

结果是:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]] 
Run Code Online (Sandbox Code Playgroud)

但我希望结果是:

[[0], [0, 1], [0, 1, 2]]
Run Code Online (Sandbox Code Playgroud)

我知道解决方案是使用浅拷贝:res.append(a[:]). 但是有人能告诉我为什么吗?

python

0
推荐指数
1
解决办法
1766
查看次数

PriorityQueue(Java),用Long覆盖比较器

PriorityQueue<Point> pq = new PriorityQueue(10, new Comparator<Point>(){
        public long compare(Point a, Point b) {
            long disA = (a.x - origin.x) * (a.x - origin.x) + (a.y - origin.y) * (a.y - origin.y);
            long disB = (b.x - origin.x) * (b.x - origin.x) + (b.y - origin.y) * (b.y - origin.y);
            if (disA == disB) {
                return (long)(a.x - b.x);
            }
            else {
                return disA - disB;
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

我正在使用PriorityQueue并覆盖Comparator,但我需要使用Long而不是int.因为disA和disB可能会溢出.但编译器说我的代码有问题.我不知道为什么.任何人帮助我PLZ.

java

-4
推荐指数
1
解决办法
72
查看次数

标签 统计

java ×3

python ×1