整数划分问题是算法中的一个经典命题之一
整数划分,是指把一个正整数n如下如下形式:
n = n<sub>1</sub> + n<sub>2</sub> + ... + n<sub>k</sub> (其中 n<sub>1</sub> >= n<sub>2</sub> ... >= n<sub>k</sub> > 0, k >= 1)
依旧是以6来举例,有如下划分:
6;
5+1;
4+2,4+1+1;
3+3,3+2+1,3+1+1+1;
2+2+2,2+2+1+1,2+1+1+1+1;
1+1+1+1+1+1;
正整数n的所有不同划分中,将最大加数x不大于m的情况记为q(n,m),这个称作n的m划分
算法的4种情况(前三种都很容易理解)
所以,q(n, m) = 1 + q(n, n-1)
所以,q(n, m) = q(n, m-1) + q(n-m,m)
Java代码实现
package EquationCount;
public class EquatinCount {
public static void main(String[] args) {
/*
* 以 ms 计算: System.currentTimeMillis();
* 以 ns 计算: System.nanoTime();
*/
long startTime = System.nanoTime(); // 获取开始时间
int n = 6;
System.out.println(equationCount(n, n));
long endTime = System.nanoTime(); // 获取结束时间
System.out.println("process time: "+(endTime-startTime)+"ns");
}
public static int equationCount(int n, int m) {
if (n == 1 || m == 1)
return 1;
else if (n > m)
return equationCount(n-m, m) + equationCount(n, m-1);
else if (n < m)
return equationCount(n, n);
else
return 1+equationCount(n, n-1);
}
}
11
process time: 157800ns
c++代码实现
#include <iostream>
#include <ctime>
using namespace std;
int equationCount(int n, int m){
if (n == 1 || m == 1)
return 1;
else if (n > m)
return equationCount(n-m, m) + equationCount(n, m-1);
else if (n < m)
return equationCount(n, n);
else
return 1+equationCount(n ,n-1);
}
int main(){
double start, stop, dur;
start = clock();
int n = 6;
cout << equationCount(n, n) << endl;
stop = clock();
dur = stop - start;
cout << "process_time: " << dur << endl;
system("pause");
}
11
process_time: 1
请按任意键继续. . .
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有