diff --git a/src/problem/mod.rs b/src/problem/mod.rs index b35cd27..78345f3 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -167,4 +167,5 @@ mod p211_design_add_and_search_words_data_structure; mod p212_word_search_ii; mod p17_letter_combinations_of_a_phone_number; mod p77_combinations; -mod p46_permutations; \ No newline at end of file +mod p46_permutations; +mod p39_combination_sum; \ No newline at end of file diff --git a/src/problem/p39_combination_sum.rs b/src/problem/p39_combination_sum.rs new file mode 100644 index 0000000..30282c7 --- /dev/null +++ b/src/problem/p39_combination_sum.rs @@ -0,0 +1,61 @@ +/** + * [39] Combination Sum + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashSet; + +impl Solution { + pub fn combination_sum(candidates: Vec, target: i32) -> Vec> { + let mut result = HashSet::new(); + let mut candidates = candidates; + candidates.sort(); + + let mut path = vec![]; + Self::dfs(&candidates, target, &mut path, 0, &mut result); + + result.iter().map(|x| x.clone()).collect() + } + + fn dfs(candidates: &Vec, target: i32, path: &mut Vec, sum: i32, result: &mut HashSet>) { + if sum > target { + return; + } + + if sum == target { + let mut p = path.clone(); + p.sort(); + result.insert(p); + return; + } + + for &i in candidates { + if i > target - sum { + break; + } + + path.push(i); + Self::dfs(candidates, target, path, sum + i, result); + path.pop(); + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_39() { + let mut set = HashSet::new(); + + set.insert(vec![1,2]); + set.insert(vec![1,2]); + + assert_eq!(set.len(), 1); + } +}