JAVA代码—算法基础:因子组合问题
2018-02-16 18:24
435 查看
因子组合问题
问题描述:一个整数进行因子分解,查找所有可能的因子组合。
例如:整数 16, 可以表示为
16 = 2*2*2*2
16 = 2*2*4
16 = 2*8
16 = 4*4
编写一个算法找出给定的一个整数所有的因子组合。
注意:1和该数本身不能算作其因子;如果有因子,所有的因子按照从小到大的顺序排列。
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.
算法设计
(完)
问题描述:一个整数进行因子分解,查找所有可能的因子组合。
例如:整数 16, 可以表示为
16 = 2*2*2*2
16 = 2*2*4
16 = 2*8
16 = 4*4
编写一个算法找出给定的一个整数所有的因子组合。
注意:1和该数本身不能算作其因子;如果有因子,所有的因子按照从小到大的顺序排列。
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.
算法设计
package com.bean.algorithmbasic; import java.util.ArrayList; import java.util.List; public class FactorCombinations { public static void main(String[] s) { int Target = 16; List<List<Integer>> list=getFactors(Target); System.out.println(list); } public static List<List<Integer>> getFactors(int n) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); helper(2, 1, n, result, list); return result; } public static void helper(int start, int product, int n, List<List<Integer>> result, List<Integer> curr){ if(start>n || product > n ) return ; if(product==n) { ArrayList<Integer> t = new ArrayList<Integer>(curr); result.add(t); return; } for(int i=start; i<n; i++){ if(i*product>n) break; if(n%i==0){ curr.add(i); helper(i, i*product, n, result, curr); curr.remove(curr.size()-1); } } } }
(完)
相关文章推荐
- JAVA代码—算法基础:四平方定理问题
- JAVA代码—算法基础:素数环问题
- JAVA代码—算法基础:0-1背包问题的回溯算法设计(续)
- JAVA代码—算法基础:最大连续子数组乘积问题
- JAVA代码—算法基础:学生出勤记录问题
- JAVA代码—算法基础:求两个字符串的最长公共子序列问题
- JAVA代码—算法基础:水壶分水的问题
- JAVA代码—算法基础:最大数问题
- JAVA代码—算法基础:整数拆分求最大乘积问题
- JAVA代码—算法基础:0-1矩阵的问题
- JAVA代码—算法基础:马走8×8棋盘问题
- JAVA代码—算法基础:数塔问题(动态规划)
- JAVA代码—算法基础:子数组的最大累加和问题
- JAVA代码—算法基础:水房接水问题
- JAVA代码—算法基础:反转整数问题
- JAVA代码—算法基础:最少货币换钱问题求解(动态规划)
- JAVA代码—算法基础:切割钢锯条售卖的问题
- JAVA代码—算法基础:三角形最短路径问题
- JAVA代码—算法基础:蚂蚁爬行问题
- JAVA代码—算法基础:活动安排问题(贪心算法)