You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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], [2]
[1], [1, 2]
[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;
}
}
The text was updated successfully, but these errors were encountered:
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:
Then I calculate prices of those methods and got the answer.
Here is the DFS code:
The text was updated successfully, but these errors were encountered: