[英]Find the length of the longest increasing subsequence using only one auxiliary recursion function
我只需要使用一个递归函数就可以找到最长的单调递增子序列的长度。 例如,给定arr={45 1 21 3 33 6 53 9 18}
它需要归还5。我已经开始编写代码,但是我被卡住了,我不知道如何找出哪个调用给出最大长度。
函数longestSet
是我的辅助函数,我可以使用我想要的任何变量,但必须从函数max_set
调用它。
void question3(int question)
{
int *arr, size;
printf("enter the array size\n");
scanf("%d", &size);
arr=(int*)malloc(size*sizeof(int));
fillArr(arr, size-1);
max_set(arr, size);
free(arr);
}
void max_set(int arr[], int size)
{
int i=0, finelmax=0, count=0,longrising;
longrising=longestSet(arr,size,i,finelmax,count);
printf("the length of the longest risind set is: %d", longrising);
}
int longestSet(int arr[], int size, int i, int finelmax, int count)
{
if(i==size)
return count;
if(arr[i]>=finelmax)
{
finelmax=arr[i];
return longestSet(arr,size,i+1,finelmax,count+1);
}
return longestSet(arr,size,i+1,finelmax,count);
}
像这样:
int longestSet(int arr[], int size, int i, int finelmax, int count)
{
if(i==size) return count;
int length1 = longestSet(arr, size, i + 1, finelmax, count);
if(arr[i] > finelmax)
{
int length2 = longestSet(arr, size, i + 1, arr[i], count + 1);
if(length2 > length1) length1 = length2;
}
return length1;
}
这样做基本上是在每个点进行比较,以包括或忽略当前数字会更好。 速度也会非常慢-例如,您可以在其中添加备注以进行改进,但是我想这不属于作业的一部分吗?
我在这里提供您要求的带有单个递归函数的完整代码。 不幸的是,它在Java中,但是您的目的将得以解决,因为用于递归的功能几乎相同。
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class longestSubSequence{
public static void main (String [] args)throws IOException{
new longestSubSequence().run();
}
int max = -1;
int index = 1;
int [] array;
private void run() throws IOException{
array = new int [50];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Input your array
StringTokenizer st = new StringTokenizer (br.readLine());
array[0] = -1;
while (st.hasMoreTokens()){
array[index++] = Integer.parseInt(st.nextToken());
}
index--;
dfs (0, 0);
System.out.println(max);// Prints the maximum length
}
private void dfs (int curr, int length){
if (length > max )max = length;
if (curr >= index)
return ;
for (int I=curr+1;I <= index; I++){
if (array[I] >= array[curr]){
dfs (I, length+1);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.