动态规划解决整数划分问题

sxiaobei 2015-07-07 12:54:25

n代表钱数，m代表划分数
1. 当n==1或者是m==1时，q（n , m）=1;
2. 当n==m时，q（n , m）=q(n,m-1)
3. 当n<m时，q (n , m)=q(n,n)
4. 当n>m时，q（n , m）= q(n ,m-1)+q(n-m,m)i

package com.test;

public class Main {

static int[] qian=new int[]{1,2,5,10,20,50,100};

public static int get(int money){
int[][] test=new int[money+1][7];
for(int i=0;i<test.length;i++){
if(i==0){
for(int j=0;j<qian.length;j++){
test[i][j]=0;
}
}else{
for(int j=0;j<qian.length;j++){
if(qian[j]==1){
test[i][j]=1;
}else{
if(i<qian[j]){
test[i][j]=test[i][j-1];

}else if(i==qian[j]){
test[i][j]=test[i][j-1]+1;
}else if(i>qian[j]){
test[i][j]=test[i-qian[j]][j]+test[i][j-1];
}
}
}
}
}
for(int i=0;i<=money;i++){
for(int j=0;j<qian.length;j++){
System.out.print(test[i][j]+" ");
}
System.out.println();
}
return test[money][qian.length-1];
}
public static void main(String[] args) {
System.out.println(get(250));

}

}
...全文
471 1 打赏 收藏 转发到动态 举报

1 条回复

Inhibitory 2015-07-07
• 打赏
• 举报

``````import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Calculator {
private static final int[] UNITS = {100, 50, 20, 10, 5, 1};
private List<String> components = new LinkedList<String>();
private int target;
private Set<String> results = new TreeSet<String>();

public Calculator(int target) {
this.target = target;
}

public void calculate() {
doCalculate(target, 0, 0);
}

public Set<String> getResults() {
return results;
}

private void doCalculate(int target, int currentSum, int index) {
if (target == currentSum) {
return;
}

for (int s = index; s < UNITS.length; ++s) {
for (int i = 0; i <= (target - currentSum) / UNITS[s]; ++i) {
if (currentSum + UNITS[s] * i <= target) {
if (i != 0) {
components.add(UNITS[s] + " * " + i);
}

doCalculate(target, currentSum + UNITS[s] * i, s + 1);

if (i != 0) {
components.remove(components.size() - 1);
}
}
}
}
}

public static void main(String[] args) throws Exception {
Calculator calculator = new Calculator(36);
calculator.calculate();
calculator.getResults().stream().forEach(System.out::println);
}
}``````

50,350

javaspring bootspring cloud 技术论坛（原bbs）

• 近7日
• 近30日
• 至今