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