【问题标题】:Leetcode Combination Sum Problem. Problem understanding the 15th lineLeetcode 组合和问题。理解第 15 行的问题
【发布时间】:2022-01-01 09:30:10
【问题描述】:

您好,我是数据结构的新手,在理解“ds.remove(ds.size()-1);”行时遇到了一些问题。有谁能帮帮我吗?

类解决方案{

private void findCombinations(int ind,int[] arr,int target,List<List<Integer>> ans, List<Integer> ds)
{
    if(ind == arr.length)
    {
        if(target == 0)
            ans.add(new ArrayList<>(ds));
        return;
    }
    if(arr[ind] <= target)
    {
        ds.add(arr[ind]);
        findCombinations(ind, arr, target - arr[ind], ans, ds);
        ds.remove(ds.size() - 1);
    }
    findCombinations(ind + 1, arr, target, ans, ds);
}

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> ans = new ArrayList<>();
    findCombinations(0, candidates, target, ans, new ArrayList<>());
    return ans;
}

}

【问题讨论】:

  • 删除ds中索引为ds.size() -1的元素。换句话说,它会从列表中删除最后一个元素。

标签: java recursive-datastructures


【解决方案1】:

通过这一行,您将删除数组中的最后一个元素。 ds.size() 是数组中元素的数量,例如有 2 个元素,如果你想获取最后一个元素的索引,你必须说 ds.size() - 1 因为第一个元素有一个索引为 0,第二个索引为 1

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 2020-11-09
    • 1970-01-01
    • 2021-09-22
    • 2022-06-12
    • 1970-01-01
    • 2019-10-29
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多