Leetcode: Factor Combinations
2015-12-23 02:33
225 查看
Numbers can be regarded as product of its factors. For example, 8 = 2 x 2 x 2; = 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors. Note: Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2]. You may assume that n is always positive. Factors should be greater than 1 and less than n. Examples: input: 1 output: [] input: 37 output: [] input: 12 output: [ [2, 6], [2, 2, 3], [3, 4] ] input: 32 output: [ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ]
这题就是不停的DFS, 直到 n == 1. 有个判断条件 if (item.size() > 1) 是为了防止答案是自己本身n, 按照题意, 这是不允许的.
参考了:http://www.meetqun.com/thread-10673-1-1.html
时间复杂度, 个人觉得是O(n*log(n)), 一开始觉得是O(n!), 但後来想想好像没那麽大. 我的想法是,
最一开始的for回圈是n, 但是一旦进入了下一个DFS, 每次最差都是 n / i在减小, 这边就是log(n), 所以总共是O(n*log(n)), 有错还请指正.
public class Solution { public List<List<Integer>> getFactors(int n) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> item = new ArrayList<Integer>(); if (n <= 3) return res; helper(2, n, res, item); return res; } public void helper(int start, int n, List<List<Integer>> res, List<Integer> item) { if (n == 1) { if (item.size() > 1) { res.add(new ArrayList<Integer>(item)); return; } } for (int i=start; i<=n; i++) { if (n%i == 0) { item.add(i); helper(i, n/i, res, item); item.remove(item.size()-1); } } } }
相关文章推荐
- uinx环境高级高级编程---------孤儿进程与僵尸进程
- 线性表之顺序存储实现
- hdu 3535 AreYouBusy(分组背包)(推荐)
- JavaScript模块化开发1
- Jenkins 简介
- 函数与方法
- windows2008 IIs部署MVC + mvc4 http错误403.14 forbidden
- Java中时间日期格式化
- 安装idea + erlang
- 个人对linux内核中的linux_digent64结构体的理解
- OpenGL渲染流程
- JavaScript闭包
- Linux关闭防火墙、SELinux
- inux设置普通用户无密码sudo权限
- hadoop安装包的目录结构
- mysql配置主从时报错及处理
- Android多点触控之——MotionEvent(触控事件)
- Introduction to Glide, Image Loader Library for Android, recommended by Google
- Hadoop的伪分布式搭建
- Linux关闭防火墙、SELinux