Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I have got a fast way to finish book-store #1

Open
Angel-Jia opened this issue Oct 3, 2018 · 0 comments
Open

I have got a fast way to finish book-store #1

Angel-Jia opened this issue Oct 3, 2018 · 0 comments

Comments

@Angel-Jia
Copy link

This method can pass all tests in less one second.
First, I get all all possible method to buy books using DFS. For example, I have three books [1, 1, 2], then I got three methods to buy them:

  1. [1], [1], [2]
  2. [1], [1, 2]
  3. [1, 2], [1]

Then I calculate prices of those methods and got the answer.
Here is the DFS code:

fn DFS(books: &[u32]){
let mut categories: Vec<u32> = vec![0; 5]; // 5 book series and the number of each
    for book in books.iter(){
        categories[(book - 1) as usize] += 1;
    }
    
let all_subsets: Vec<Vec<Vec<usize>>> = get_all_subsets(&mut categories, books.len());
}

fn get_all_subsets(categories: &mut Vec<u32>, total_books: usize) -> Vec<Vec<Vec<usize>>>{
    let mut out_tmp: Vec<Vec<usize>> = Vec::new();  
    let mut ret: Vec<Vec<Vec<usize>>> = Vec::new(); 
    recursive(categories, &mut out_tmp, &mut ret, total_books, 0);
    ret
}

pub fn recursive(categories: &mut Vec<u32>, out: &mut Vec<Vec<usize>>, ret:&mut Vec<Vec<Vec<usize>>>, total_books: usize, num_books: usize){
    if total_books == num_books{
        ret.push(out.clone());
        return;
    }
    let mut books_num = num_books;
    let mut book_set: Vec<usize> = Vec::new();
    for i in 0..5{
        if categories[i] != 0{
            book_set.push(i);
            categories[i] -= 1;
            books_num += 1;
            out.push(book_set.clone());
            recursive(categories, out, ret, total_books, books_num);
            out.pop();
        }
    }
    for item in book_set.iter(){
        categories[*item] += 1;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant