Lecture 2a Recursion

Lecture 2a Recursion - Recursion (part a) In the coming 1...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
1/10 Recursion (part a) In the coming 1 hour ± What is recursion? ± Advantages of recursion
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2/10 Starting example ± Given 6 characters, print all permutations of 4 characters using only 1 for-loop? Divide-and-conquer: Can it be reduced to some easier problems? [0] ± Input[0. .5] 2. Generate all permutations of 3 characters using [1. .5] 1. Generate all permutations of 4 char. Using [0. .5] [1] [2] [3] [4] [5] [1] [2] [3] [4] [5] 3. Generate all permutations of 2 characters using [1],[2],[4],[5] [1] [2] [4] [5] [1] [2] [5] 4. Generate all permutations of 1 characters using [1],[2],[5]
Background image of page 2
3/10 Pseudocode //Pre: Given n char and an integer m, 1<= m <= n //Post: Generate all m-letter permutations SetOfStrings generatePermutations( char input[], int n, int m ) { SetOfStrings result; if( m=1 ){ for( int i=0; i<n; i++ ){ insert input[i] into result } return result }else{ for( int i=0; i<n; i++ ){ //generate all permutations that starts with input[i] let input2[] be a set of remaining chars, i.e., input[] – char input[i] SetOfStrings result2 = generatePermutations( input2, n-1, m-1 ) concatenate input[i] with each string in result2 } return all strings formed in the above for-loop; } }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4/10 //generatePermutations.cpp //Pre: Given n char and an integer m, 1<= m <= n //Post: Generate all m-letter permutations list<string> generatePermutations( string input, int n, int m ){ list<string> result; if( m==1 ){ for( int i=0; i<n; i++ ){ result.push_back( input.substr( i, 1 ) ); } }else{ for( int i=0; i<n; i++ ){ string input2 = input.substr(0, i) + input.substr(i+1, n-i-1); list<string> result2 = generatePermutations(input2,n-1,m-1);
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/10/2011 for the course CSIS 1122A taught by Professor Unknown during the Spring '11 term at HKU.

Page1 / 12

Lecture 2a Recursion - Recursion (part a) In the coming 1...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online