您的位置:首页 > 编程语言 > Java开发

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.

算法设计

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);
}
}
}

}


(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: