栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【算法】回溯:组合问题(java需要调用复制方法)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【算法】回溯:组合问题(java需要调用复制方法)

回溯:77. 组合

在本题中,c++很好理解,但是在书写java的时候有一个需要注意的知识盲区:

 //Java
 class Solution {
     public List path = new linkedList<>();
     public List > res = new linkedList<>();
     public List> combine(int n, int k) {
         traversal(n, k, 1);
         return res;
    }
 ​
     public void traversal(int n, int k, int startIndex){
         if(path.size() == k){
             res.add(new linkedList<>(path));/
             return;
        }
 ​
         for(int i = startIndex; i <= n; i++){
             path.add(i);
             traversal(n, k , i + 1);
             path.remove(path.size() - 1);
        }
    }
 }
 res.add(new linkedList<>(path));

将当前path保存在res中的时候需要调用List类中的复制方法,否则res中仅仅保存了多个path的引用,导致最后res输出了六个空List([[],[],[],[],[],[]])。这是和c++不一样的。

 //附c++
 class Solution {
 public:
     vector path;
     vector > res;
     vector> combine(int n, int k) {
         path.clear();
         res.clear();
         traversal(path, res, n, k, 1);
         return res;
    }
 ​
     void traversal(vector &path, vector > &res, int n, int k, intstartindex){
         if(path.size() == k){
             res.push_back(path);
             return;
        }
 ​
         for(int i = startindex; i <= n; i++){
             path.push_back(i);
             traversal(path, res, n, k, i + 1);
             path.pop_back();
        }
    }
 };

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号