n个数字相加组合问题 & 荷兰旗问题
来源:互联网 发布:网络教育考试难吗 编辑:程序博客网 时间:2024/05/02 01:59
题目描述: 给定两个数字 m,n, 其中m和n满足关系 m>=n>0。请输出n个数字相加等于m(即i1+i2+i3+.......in = m) 的所有可能组合。
input : m=4 ,n=2
output : 1,3 2,2
代码如下:
package 实际问题;import java.util.Stack;public class jiashu { /** * 输入两个整数 m,n 其中 m>=n>0,使 i1 + i2 +....in = m,请求出其所有结果 * for example : m = 4 , n = 2 * output: 1,3 2,2 */ public static void main(String[] args) { new jiashu().get(8, 3, 1); System.out.println("-----------------------------------------------------"); new jiashu().get2(8, 3, 1, ""); } private Stack<Integer> stack = new Stack<Integer>(); public void get(int m, int n, int max) { if(n==1 && m>=1) { if(!stack.isEmpty()) { for(int i=0; i<stack.size(); i++) { System.out.print(stack.get(i)+","); } System.out.println(m); stack.pop(); //将上一层压栈的数据弹出 } return; } else { for(int i=max; i<=m/n; i++) { stack.add(new Integer(i)); get(m-i, n-1, i); } if(!stack.isEmpty()) stack.pop(); //将上一层压栈的数据弹出 } } public void get2(int m, int n, int max, String str) { if(n==1 && m>=1) { System.out.println(str+m); } else { for(int i=max; i<=m/n; i++) { get2(m-i, n-1, i, str+i+","); } } }}
题目描述
现有红白蓝三个不同颜色的小球,乱序排列在一起,请重新排列这些小球,使得红白蓝三色的同颜色的球在一起。这个问题之所以叫荷兰国旗,是因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。如下图所示:
/* * 荷兰旗问题:http://blog.csdn.net/v_july_v/article/details/18824517 * */public class Netherlands {public static void main(String args[]){Netherlands nls =new Netherlands();int []res = {2, 1, 3, 1, 1, 2, 3, 3, 1};res = nls.partitionLands(res, res.length);} /* 使用分治的算法,参看算法:快速排序 */public int[] partitionLands(int []res, int len ){int begin=0, cur=0, end=len-1;while(cur<end){if(res[cur] == 1){int temp = res[begin];res[begin] = res[cur];res[cur] = temp;cur++; begin++;}else if(res[cur] == 3){int temp = res[end];res[end] = res[cur];res[cur] = temp;end--;}else{ //res[cur] == 2cur++;}}return res;}}
- n个数字相加组合问题 & 荷兰旗问题
- 数字组合问题(N个正整数连接起来最大)
- n 个double相加的问题
- 输出1到N之间所有相加等于M的数字组合(背包问题)求相加为M的所有组合--微软酷派经典面试题
- 荷兰旗问题
- 数字相加问题。
- JS 数字相加出现多个小数的问题
- 算法之数学自由组合问题(从M个不重复的数字中选取N个数字进行自由组合)
- N个线程轮流打印数字问题
- 数字组合问题
- 数字组合问题
- 数字组合问题!
- 数字组合问题
- 数字组合问题
- 多个大数相加问题
- 组合问题-----从字母表中选择n个字母
- 组合问题——从n种球种取出m个
- 荷兰旗问题(三色旗排序)
- C++ STL map的使用
- <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- oracle 实用工具 DBVERIFY
- C++ STL入门教程(1)——vector(向量容器)的使用(附完整程序代码)
- dataguard的其他一些操作
- n个数字相加组合问题 & 荷兰旗问题
- 怎样才能学好程序设计?
- 关于Demo中地图显示的实现原理
- 惯例优先原则(convention over configuration)
- 服务器的分类
- SDUTRescue The Princess(数学问题)
- MQ 性能优化
- JAVA反射机制
- 可展开的列表组件ExpandableListView