Lecture 2a Recursion

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

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

1/10 Recursion (part a) In the coming 1 hour ± What is recursion? ± Advantages of recursion

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

View Full Document
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]
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; } }

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

View Full Document
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);
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
Ask a homework question - tutors are online