mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-06 21:22:10 +08:00
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
55 lines
1.7 KiB
Rust
55 lines
1.7 KiB
Rust
/*
|
|
* File: subset_sum_i_naive.rs
|
|
* Created Time: 2023-07-09
|
|
* Author: codingonion ([email protected])
|
|
*/
|
|
|
|
/* 백트래킹 알고리즘: 부분 집합 합 I */
|
|
fn backtrack(
|
|
state: &mut Vec<i32>,
|
|
target: i32,
|
|
total: i32,
|
|
choices: &[i32],
|
|
res: &mut Vec<Vec<i32>>,
|
|
) {
|
|
// 부분 집합의 합이 target과 같으면 해를 기록한다
|
|
if total == target {
|
|
res.push(state.clone());
|
|
return;
|
|
}
|
|
// 모든 선택지를 순회한다
|
|
for i in 0..choices.len() {
|
|
// 가지치기: 부분 집합의 합이 target을 초과하면 해당 선택을 건너뛴다
|
|
if total + choices[i] > target {
|
|
continue;
|
|
}
|
|
// 시도: 선택하고 원소의 합 total을 갱신한다
|
|
state.push(choices[i]);
|
|
// 다음 선택을 진행한다
|
|
backtrack(state, target, total + choices[i], choices, res);
|
|
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
|
state.pop();
|
|
}
|
|
}
|
|
|
|
/* 부분 집합 합 I 풀기(중복 부분 집합 포함) */
|
|
fn subset_sum_i_naive(nums: &[i32], target: i32) -> Vec<Vec<i32>> {
|
|
let mut state = Vec::new(); // 상태(부분 집합)
|
|
let total = 0; // 부분 집합의 합
|
|
let mut res = Vec::new(); // 결과 리스트(부분 집합 리스트)
|
|
backtrack(&mut state, target, total, nums, &mut res);
|
|
res
|
|
}
|
|
|
|
/* 실행 코드 */
|
|
pub fn main() {
|
|
let nums = [3, 4, 5];
|
|
let target = 9;
|
|
|
|
let res = subset_sum_i_naive(&nums, target);
|
|
|
|
println!("입력 배열 nums = {:?}, target = {}", &nums, target);
|
|
println!("합이 {}인 모든 부분 집합 res = {:?}", target, &res);
|
|
println!("이 방법의 출력 결과에는 중복 집합이 포함된다");
|
|
}
|