改善我的贪心算法

时间:2016-10-27 01:47:18

标签: java arrays

**这是我的代码,它可以找到在数组中找到总和的方法**

     public class Piecedemonei {
        public static void recherche(int[] tab) {
                int num;
                int quo;

                for (int i = 0; i <= tab.length - 1; i++) {


 int somme = 18;
                    System.out.println("Solution  " + i);

                    for (int j = i; j < tab.length; j++){


                        if (tab[j] <= somme) {

                            num = somme / tab[j];
                            System.out.print(num+"*" + " " + tab[j]);
                            System.out.println(" ");

                            somme -= num * tab[j];
        j=0;
                        }



                }
            }
            }




            public static void main(String[] args) {
                int aba[] = { 7, 6, 4, 5 };
                recherche(aba);
                System.out.println();

            }

        }

输出

Solution  0
2 7 + 1 4
Solution  1
Solution  2
Solution  3

**我正在寻找一种方法来改进我的代码,以便输出如下所示:**

 Solution  0
2*7 + 1*4
Solution  1
3*6
Solution  2
4*4 + 1*4
Solution  3

**为什么我无法重置循环以便它一次又一次地做同样的事情? **

1 个答案:

答案 0 :(得分:0)

更改

int somme = 18;
for (int i = 0; i <= tab.length - 1; i++) {
    System.out.println("Solution  " + i);

    for (int j = 0; j < tab.length; j++){
    ...

for (int i = 0; i <= tab.length - 1; i++) {
    int somme = 18;
    System.out.println("Solution  " + i);

    for (int j = i; j < tab.length; j++) {
    ...

注意内循环中的int j = i