三色球问题

三色球问题

若一个口袋里放了12个球,3个红的,3个黄色的,6个绿色的,从中任意选择8个,问有多少不同的搭配?

1:问题的分析

取红色的球可以有4种可能:0个,1个,2个,3个

取黄色的球可以有4种可能:0个,1个,2个,3个

取绿色的球可以有7种可能:0个,1个,2个,3个,4个,5个,6个

我们只需要穷举每一种可能的情况就行了

package 三色球;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int red,yellow,green;//存储红,黄,绿球的个数
        int n;
        System.out.println("三色球问题的求解!\n");
        System.out.println("请输入红色球的数量为:");
        Scanner input = new Scanner(System.in);
        red = input.nextInt();
        System.out.println("请输入黄色的球的数量:");
        yellow = input.nextInt();
        System.out.println("请输入绿色球的数量:");
        green = input.nextInt();
        System.out.println("请先输入取出球的数量:");
        n = input.nextInt();
        //求解
        threeball(red,yellow,green,n);
        

    }

    private static void threeball(int red, int yellow, int green,int n) {
        int i,j,k;
        System.out.println("总共有如下几种可能!\n");
        System.out.printf("\t红球\t黄球\t绿球");
        for(i=0;i<=red;i++)
        {
            for(j=0;j<=yellow;j++)
            {
                for(k=0;k<=green;k++)
                {
                    if(i+j+k == n)
                    {
                        System.out.printf("\t%d\t%d\t%d\n",i,j,k);
                    }
                }
            }
        }
        
    }

}

结果:

三色球问题的求解!

请输入红色球的数量为:
3
请输入黄色的球的数量:
3
请输入绿色球的数量:
6
请先输入取出球的数量:
8
总共有如下几种可能!

红球 黄球 绿球 0 2 6
0 3 5
1 1 6
1 2 5
1 3 4
2 0 6
2 1 5
2 2 4
2 3 3
3 0 5
3 1 4
3 2 3
3 3 2

posted on 2014-12-30 21:37  aicpcode  阅读(1197)  评论(0编辑  收藏  举报

导航