当前位置: 首页 > news >正文

LintCode第652题-递归版

描述

一个非负数可以被视为其因数的乘积。编写一个函数来返回整数 n 的因数所有可能组合。

组合中的元素(a1,a2,...,ak)必须是非降序。(即,a1≤a2≤...≤ak)。

结果集中不能包含重复的组合。

样例1

 
输入:8
输出: [[2,2,2],[2,4]]
解释: 8 = 2 x 2 x 2 = 2 x 4

样例2

 
输入:1 
输出: []

思路:

易错点:

1.容易忽略掉回溯语句,回溯后没清除path,会导致组合路径出错

pathList.remove(pathList.size()-1)  

 2. dfs(1,supplementNum,pathList,totalList);该方法里面是supplementNum而不是startFactor

如果是传入的是startFactor会有无线递归的风险

代码如下:

import java.util.*;

public class Solution {

    public List<List<Integer>> getFactors(int n) {

        List<List<Integer>> totalList=new ArrayList<>();

        List<Integer> pathList=new ArrayList<>();

        dfs(n,2,pathList,totalList);

        return totalList;

    }

    void dfs(int supplementNum ,int startFactor,List<Integer> pathList,List<List<Integer>> totalList)

    {

        if(supplementNum==1)

        {

            if(pathList.size()>1)

            {

                totalList.add(new ArrayList<>(pathList));

            }

            return;

        }

        for(int factor=startFactor;factor<=Math.sqrt(supplementNum);factor++)

        {

            if(supplementNum%factor==0)

            {

                pathList.add(factor);

                dfs(supplementNum/factor,factor,pathList,totalList);

                pathList.remove(pathList.size()-1);

            }

        }

        if(supplementNum>=startFactor)

        {

            pathList.add(supplementNum);

            dfs(1,supplementNum,pathList,totalList);

            pathList.remove(pathList.size()-1);

        }

    }

   

    }


 

 

相关文章:

  • 1996-2022年全国31省ZF干预度数据/财政干预度数据(含原始数据+计算过程+结果)
  • 算法笔记.试除法判断质数
  • 网络编程——TCP和UDP详细讲解
  • Adam(Adaptive Moment Estimation)
  • Python数据分析课程实验-2
  • 前端八股 5
  • Gen6D代码框架分析
  • Linux——线程(3)线程同步
  • Elsevier latex报错Paragraph ended before \@citex was complete.<to be read again>
  • Pinia: vue3状态管理
  • 【Android】四大组件
  • Mem0.ai研究团队开发的全新记忆架构系统“Mem0”正式发布
  • 2025年人工智能火爆技术总结
  • 【Linux网络】I/O多路转接技术 - epoll
  • epoll函数
  • 【Shell 脚本编程】详细指南:第四章 - 循环结构(for、while、until) 深度解析
  • 60常用控件_QSpinBox的使用
  • 排序算法——冒泡排序
  • C语言学习之动态内存的管理
  • 交我算使用保姆教程:在计算中心利用singularity容器训练深度学习模型
  • 中国队夺跳水世界杯总决赛首金
  • 侧记|“五五购物节”启动!最大力度补贴,买买买 “666”
  • 国家卫健委对近日肖某引发舆情问题开展调查
  • 美国第一季度经济环比萎缩0.3%
  • 央行召开落实金融“五篇大文章”总体统计制度动员部署会议
  • 现场|西岸美术馆与蓬皮杜启动新五年合作,新展今开幕