









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










COP 3503 – Computer Science II – CLASS NOTES - DAY # Problem Solving Techniques We now shift our focus from run-time complexity to introducing several general techniques which can be applied to problem solving. Different problems require different approaches in defining their solutions. To this end the algorithm designer needs to have a good understanding of many different techniques that can be applied toward solving the problem at hand. This set of notes introduces the problem solving techniques of recursion , divide and conquer , dynamic programming , and backtracking. Recursion A method or function either directly or indirectly calls itself. Can be a powerful problem solving tool. Many algorithms and mathematical properties are naturally expressed in a recursive manner. Some programming languages are inherently recursive (Lisp, Scheme). If properly done, a recursive function F calling itself, does not lead to an infinite cycle of the function calling itself. Instead, each recursive call is made on a different, generally simpler, instance of the problem. Example: Consider the factorial function, n!. 0! = 1 n! = n * (n-1) * … * 3 * 2 * To determine 6! using this definition requires that we calculate: 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720 Defining the factorial function recursively, we have: 1 if n = 0 fact (n) = 1 if n = 1 n * fact(n-1) if n >= 2 Now 6! = 6 * 5! = 6 * (5 * 4!) = 6 * (5 * (4 * 3!)) = 6 * (5 * (4 * (3 * 2!))) = 6 * (5 * (4 * (3 * (2 * 1!)))) = 6 * (5 * (4 * (3 * (2 * (1 * 0!))))) = 6 * 5 * 4 * 3 * 2 * 1 * 1
A recursive function is a function which is defined in terms of itself. For example, it is common to express the factorial function, f(n) = n! where n is an integer , as the recursive function: ^ nf(n 1 ) n 1 f(n )^1 n^1 This definition states that f(n) equals 1 whenever n is less than or equal to 1. For example, f(-3) = f(0) = f(1) = 1. However, when n is more than 1, f(n) is defined recursively, since the definition of f now contains an occurrence of f on the right side. Note that the use of f on the right side does not constitute a circular definition since the parameter of f on the right side is smaller than the one on the left side. For example, the from the definition we have: f(2) = 2f(1) and the definition also gives us f(1) = 1, substitution then provides the answer that f(2) = 2(1) = 2. Similarly, for f(3) the definition gives us: f(3) = 3f(2), from above we know that f(2) = 2f(1) and f(1) = 1, thus f(3) = 3f(2) = 3(2(f(1))) = 3(2(1))) = 6. For a recursive definition of f(n) (assuming direct recursion) to be a complete specification of the function f , it must meet the following requirements: The definition must include a base component in which f(n) is defined directly (i.e., without recursion) for one or more values of n. For simplicity, we assume that the domain of f is the nonnegative integers and that the base covers the case 0 n k for some constant k. (Note: it is possible to have recursive definitions in which the base covers the case n k instead, but these definitions occur infrequently.) In the recursive component all occurrences of f on the right side must have a parameter smaller than n so that repeated application of the recursive component transforms all occurrences of f on the right side to occurrences of f in the base component. For the recursive function shown above, the base component is f(n) = 1 for n 1; the recursive component is f(n) = n f(n-1) and the parameter of f on the right hand side is (n-1) which is smaller than n. Repeated application of the recursive component transforms f(n-1) to f(n-2), f(n-3), …, and finally to f(1) which is included in the base component. For example, repeated application of the recursive component gives the following: f(5) = 5f(4) = 20f(3) = 60f(2) = 120f(1) = 120 Notice how each application of the recursive component gets closer to the base. Finally, an application of the base component gives the answer that f(5) = 120.
Proofs by Mathematical Induction Induction proofs are most often used to establish theorems that hold for positive integers. That is, you can establish the validity of a conjecture such as:
n i 0 i 2 n( n 1 ) by showing that the conjecture is true for one or more base values of n (generally, n = 0 is sufficient – though not always). Once this base case is proven true, you assume that the conjecture is true for all values of n from the base case through m , where m is an arbitrary integer greater than or equal to the largest value of n covered in the base case; this is the inductive hypothesis. Finally, using the assumption of the inductive hypothesis you prove that the conjecture is true for the next value of n (i.e., m + 1). This final step is the induction step. To summarize: An induction proof consists of three parts:
n i 1 i 2 n( n 1 )
n i 1
1 i 1 i (^) 1, by substitution 1 i 1 i 2 1 ( 1 1 ) = 2 2 = 1 So the base case is true! Inductive Hypothesis : n=k, assume n i 1 i 2 k( k 1 ) is true. Inductive Step : prove conjecture is true for n = k+ Must prove that: k 1 i 1 i 2 (k 1 )[(k 1 ) 1 ] = 2 (k 1 )(k 2 )
Note that k 1 i 1 i (^) k i 1 i (^) + (k +1) = 2 k( k 1 )
2 k
2 2 k
2 2 2 k^2
2 k
2 2 k
2 2 = 2 k^2 3 k 2 = 2 (k 1 )(k 2 ) Thus the proof is completed and our conjecture is true for all integer numbers. At first glance, a proof by induction appears to be a circular proof, in that you establish a result by assuming that it is correct. However, an induction proof is not a circular proof for the same reason that a recursive definition is not circular. A correct proof by induction has an induction base that is similar to the base case of a recursive definition. The induction step proves the correctness using the correctness for smaller values of n. Repeated application of the induction step reduces the proof to one that is solely in terms of the base. Induction proofs have their foundation in recursion, which can be a powerful problem solving tool.
More on Recursion Let’s look at a couple recursive static methods in Java that calculate Fibonacci and Factorials, respectively: Here is a recursive binary search: public static int Fibonacci(int n) { if (n < 0) return –1; // This signifies an illegal input parameter. else if (n < 2) return n; else return Fibonacci(n-1) + Fibonacci(n-2); } public static int Factorial(int n) { if (n < 0) return –1; // This signifies an illegal input parameter. else if (n < 2) return 1; else return n*Factorial(n-1); public static int Search(int[] X, int low, int high, int value) { if (low > high) return -1; else { int mid = (low + high)/2; if (value > X[mid]) return Search(X,mid+1,high,value); else if (value < X[mid]) return Search(X,low,mid-1,value); else return mid; } }
Consider the following problem: Given a positive integer value of cents, how many different ways can we make change equaling that number of cents, using only pennies, nickels, dimes, and quarters. Here is a recursive solution: There is A LOT going on in this short piece of code. The essential idea is the following: If you have n cents, you could make change for it by doing the following:
Divide and Conquer Divide and conquer is an important problem-solving technique that relies on recursion. [Note: Not all recursive algorithms are divide and conquer.] Divide and conquer is a top down approach to problem solving meaning that an initial problem is subdivided into smaller subproblems, each of which is similar in nature to the original problem – only it is smaller. Each of the smaller subproblems is solved independently. A divide and conquer algorithm is a recursive algorithm that consists of two parts: (1) Divide: smaller problems are solved recursively (except for the base case). (2) Conquer: the solution to the original problem is then formed from the solutions to the subproblems. Traditionally, algorithms that contain two recursive calls are called divide and conquer algorithms while those that contain only a single recursive call are not. Also, in order to avoid excessive computational cost, the subproblems should be disjoint (non-overlapping). The divide and conquer strategy has been applied to many different types of problems including: matrix multiplication, minimax problems, sorting, and searching. Since the original problem is divided into several subproblems, divide and conquer algorithms are well suited to implementation on parallel computers. Example 1 – Divide and Conquer – MCSS Problem The Maximum Contiguous Subsequence Sum Problem Revisited Recall the problem: Maximum Contiguous Subsequence Sum: given (a possibly negative) integers A 1 , A 2 , …, AN, find (and identify the sequence corresponding to) the maximum value of For the degenerate case when all of the integers are negative, the maximum contiguous subsequence sum is zero. Example: If input is: {-2, 11, -4, 13, -5, 2}. Then the output is: 20. If the input is {1, -3, 4, -2, -1, 6}. Then the output is 7.
j k iAk
A divide and conquer algorithm for the MCSS problem divides the input data set into two halves. Once this is done the MCSS can occur in one of three ways: (1) the MCSS is entirely in the first half of the input set. (2) the MCSS is entirely in the second half of the input set. (3) the MCSS begins in the first half and ends in the second half of the input. Graphically this is illustrated as follows: A B case 1: A B case 2: A B case 3: What we need to show is that each of these three cases can be solved more efficiently than by an exhaustive search. Consider case 3: we know that the last element of the A array is in the MCSS and the first element of the B array is in the MCSS. Therefore to compute sums in A and B we read from right-to-left in A and left-to-right in B. Thus the biggest sum calculated from A + biggest sum calculated from B = MCSS. Since these calculations can be done consecutively (compute sum in A, the compute sum in B). This can be done in linear time. So for case 3 the divide and conquer approach yields an O(N) running time. MCSS MCSS MCSS Example – case 3 Array A Array B 4 -3 5 -2 -1 2 6 -2 Values 4 0 3 -2 -1 1 7 5 Running Sums MCSS = 11 since MaxSum(A) + MaxSum(B) = 4 + 7 = 11
Example 2 – Divide and Conquer – Detecting a Counterfeit Coin Suppose that you are given a bag containing 16 coins and told that one of the coins may be counterfeit. Further, you are told that counterfeit coins are lighter than genuine coins. To assist you in your task you have a machine that will compare the weights of two sets of coins and tell you which set is lighter or whether both sets have the same weight. There are two related questions that you could be asked to solve: (1) Is there a counterfeit coin present in the bag? (2) Identify the counterfeit coin. Consider the following strategy for determining the presence of a counterfeit coin: Compare the weights of coins 1 and 2. If coin 1 is the lighter – it is the counterfeit and your task is complete! Similarly, if coin 2 is the lighter your task is complete and the counterfeit has been identified. If coins 1 and 2 have the same weight then you must continue by comparing coins 3 and 4 and so on. In the worst case, you will not complete your task until coins 15 and 16 have been compared – this means that you will have made 8 comparisons. Proceeding in this fashion allows you to answer both questions simultaneously as you will be able to identify the counterfeit coin as the result of a comparison (question 2) which also provides the answer to the first question. The table below illustrates the time required to answer the two questions for this problem instance in terms of the number of comparisons required to answer the question. Question Best case time Average time Worst case time 1 1 4 8 2 1 (success case) 4 8 Was the technique just described a divide and conquer strategy? Yes and no! Certainly the original problem involving the 16 coins was divided into a set of smaller subproblems each similar to the original problem. However, a better use of the divide and conquer strategy will result in an improved performance for our algorithm. Consider the following strategy: Divide the 16 coins into two sets of 8 coins (randomly selected for each set) called sets A and B. Making a single comparison of the weights of the two sets will allow us to answer question 1. In order to answer question 2 more comparisons will need to be performed as follows: The lighter set from the first comparison obviously contains the counterfeit coin. Take this set and divide it into two different sets called C and D. For our example, sets C and D will each contain four coins (approximately – there is no real need to make them exactly the same size). A similar procedure will be followed for C and D resulting in a second comparison. Again the lighter of C and D will contain the counterfeit coin and this set will be further divided into two sets called E and F.
Now sets E and F contain 2 coins each [note that this is the base case for this problem as since a set size of 1 leaves us without any comparison criteria]. A third comparison will identify the lighter set between E and F. Dividing the lighter of E and F into sets G and H will produce sets with only a single coin in each. Comparison of G and H will answer question 2 after a fourth comparison has occurred. The following table illustrates the improvement in the number of comparisons this true divide and conquer strategy exhibits compared to our first strategy. Question Best case time Average time Worst case time 1 1 1 1 2 1 (failure case) 4 (success case)
Which strategy would you use now to solve this problem? How does this compare to a brute force strategy? Another question should now become obvious to you, “Can the worst case number of comparisons for question 2 be improved?” The answer is yes! Can you determine how to reduce the worst case number of comparisons to something below 4? Think about this one for a minute and we’ll look at how to do this below. In the previous improvement to our technique (its actually an algorithm, we just haven’t presented it formally) we took the original set of 16 coins and divided them in half, further dividing the set of eight which contained the counterfeit coin (the set of eight that was lighter in weight) in half to produce to sets of 4 coins each, and so on until we had only two coins remaining and we could directly determine which was the counterfeit coin. The technique we employed was derived from the halving principle. However, we are under no restriction as to how we divide the original problem. Suppose that instead we divide the original 16 coins into four stacks, with two of these stacks containing 6 coins each ( total) and two of these stacks containing two coins each (4 total). [Note that if we divided the original 16 coins into four stacks with two stacks containing 7 coins and two stacks containing 1 coin each we are back to the original “brute force” technique, so we will not consider a division which places fewer than two coins in any stack.] With this division of the coins, consider the best case number of comparisons to find the counterfeit coin (question 2). We would start by comparing the two stacks containing 2 coins each and would find that one of the stacks was lighter. The lighter stack would be divided into two stacks containing 1 coin each and a second comparison would produce our answer. Thus, the best case number of comparisons has dropped from 4 to 2 simply by adjusting the technique we used to divide the original problem! Notice too, that while the number of
In all other cases the problem is divided into half via the two recursive calls plus the linear time of case 3. Since each of these subproblems is of size N/ they each will require T(N/2). But there are two of these subproblems so the time is 2T(N/2). So T(N) = 2T(N/2) + O(N). Replacing the O(N) term with N and assuming that N is a power of 2 we have: T(1) = 1 and T(N) = 2T(N/2) + N Theorem 7.4 states that if N is a power of 2 the solution to the equation T(N) = 2T(N/2) + N with initial condition T(1)=1 is T(N) = N log 2 N + N This is exactly what was shown in the previous diagram in the MCSS example.