Recursively finds the longest growing sequence in the array in java

for example this is array [1, 4, 9, 2, 6, 7, 3, 5, 8, 10]. and 1,2,3,5,8,10 is the answer

so how can i solve this with recursion.

thanks for any help.

public class 4b {

   public static int getLongetsLadder(int[] array){
   int i=0;
   int[] result = recursive(array,i); 

   return 0;
   }
   public static int[] recursive(int[] array, int i)
   {
   return null;
   }

   public static int[] recurse(int  i, int arr[])
   {
       int[] answer = new int[1];
       answer[0]= arr[i];

       return answer;

   }
}

Implement ion in Java is given below:

public static Integer[] recurse(int i, int li, int arr[]) {

    if(i == arr.length)
        return new Integer[0];

    boolean choice = (li == -1) || arr[li] < arr[i];
    /* now you have choice to choose it or skip it */
    if(choice) {
        /* choose it */
        ArrayList l = new ArrayList();
        l.add(i);
        for(Integer v : recurse(i + 1, i, arr)) {
            l.add(v);
        }

        /* dont choose it */
        ArrayList r = new ArrayList();
        for(Integer v : recurse(i + 1, li, arr)) {
            r.add(v);
        }

        /* return largest */
        return l.size() > r.size() ? l.toArray(new Integer[0]) : r.toArray(new Integer[0]);
    }

    /* skip and proceed */
    return recurse(i + 1, li, arr);
}

Thats how it should be called:

public static void main(String[] args) {
    findLargest(1, 4, 9, 2, 6, 7, 3, 5, 8, 10);
}
public static void findLargest(int ... vals) {
    Integer[] longest = recurse(0, -1, vals);
    for(Integer i : longest) {
        System.out.println(vals[i]);
    }
}

Result of above call was 1, 2, 3, 5, 8, 10

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Recursively finds the longest growing sequence in the array in java

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录