【问题标题】:All combination of score for a given score list给定分数列表的所有分数组合
【发布时间】:2015-05-30 13:15:56
【问题描述】:

我正在尝试使用

获得给定分数的所有分数组合

递归

这是我的代码 sn-p

public class CombinationForGivenScore {


        public static void FindCombination(int score[],int x,int ans[],int index){
            if(x == 0){
                for(int i = 0;i<index;i++){
                    System.out.print(ans[i]);
                }
                System.out.println();
            }
            else if(x>0){
                for(int i =0;i<score.length;i++){
                        x = x -score[i];
                        ans[index] = score[i];
                        index++;
                        FindCombination(score, x, ans, index);
                }

            }
        }

        public static void main(String args[])throws Exception{
            int score[] = {1,2,3}; // valid score 
            int ans[] = new int[100]; // just a large array to store the combination
            int index = 0; // index for the ans array
            int x = 3; // total score
            FindCombination(score, x, ans, index);
        }

    }

我期待这个结果

x = 3 输出 111 12 21 3

我得到的是

111 12

根据我的理解,循环将为分数数组中的每个数字创建一个递归调用。 但它不是那样工作的。

【问题讨论】:

    标签: algorithm recursion combinations


    【解决方案1】:

    使用这些语句:

    x = x -score[i];
    // ...
    index++;
    

    您更改了局部变量x 和index,这意味着它们在随后的循环中将具有错误的值。但是您只想在下一个递归实例中更改它们,即在您要调用的函数中:

    for (int i = 0; i < score.length; i++) {
        ans[index] = score[i];
        FindCombination(score, x - score[i], ans, index + 1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多