fn powerset(nums: &[i32]) -> Vec<Vec<i32>> {
let mut result = vec![vec![]];
for &num in nums {
let mut new_subsets = vec![];
for subset in &result {
let mut new_subset = subset.clone();
new_subset.push(num);
new_subsets.push(new_subset);
}
result.extend(new_subsets);
}
result
}
fn main() {
let input = vec![1, 2];
let subsets = powerset(&input);
println!("{:?}", subsets);
}The code starts with an empty subset []. Then for each number, it adds that number to all existing subsets to form new subsets. For [1, 2], the subsets are [], [1], [2], and [1, 2].
Each element has two choices: to be included or excluded. So total subsets are 2 multiplied by itself n times, which is 2^n.
fn powerset_recursive(nums: &[i32]) -> Vec<Vec<i32>> {
if nums.is_empty() {
return vec![vec![]];
}
let first = nums[0];
let rest = &nums[1..];
let subsets_without_first = powerset_recursive(rest);
let mut subsets_with_first = vec![];
for subset in &subsets_without_first {
let mut new_subset = subset.clone();
new_subset.insert(0, first);
subsets_with_first.push(new_subset);
}
[subsets_without_first, subsets_with_first].concat()
}
fn main() {
let input = vec![1, 2, 3];
let subsets = powerset_recursive(&input);
println!("{:?}", subsets);
}The recursion first gets subsets of [2, 3], then adds 1 to each of those subsets at the front. The order reflects this process.
fn powerset(nums: &[i32]) -> Vec<Vec<i32>> {
let mut result = vec![vec![]];
for num in nums {
for subset in &result {
let mut new_subset = subset.clone();
new_subset.push(*num);
result.push(new_subset);
}
}
result
}
fn main() {
let input = vec![1, 2];
let subsets = powerset(&input);
println!("{:?}", subsets);
}The inner for loop over &result creates an immutable borrow of result that lasts for the entire loop. Inside the loop, result.push attempts a mutable borrow, which conflicts with the existing immutable borrow. This results in a compilation error: cannot borrow `result` as mutable because it is also borrowed as immutable.
fn count_subsets(nums: &[i32], target: i32) -> i32 {
fn helper(nums: &[i32], target: i32, index: usize) -> i32 {
if target == 0 {
return 1;
}
if index == nums.len() || target < 0 {
return 0;
}
helper(nums, target, index + 1) + helper(nums, target - nums[index], index + 1)
}
helper(nums, target, 0)
}
fn main() {
let nums = vec![1, 2, 3];
let target = 3;
let count = count_subsets(&nums, target);
println!("{}", count);
}The recursive function counts subsets summing to target by choosing to include or exclude each element. For [1,2,3] and target=3, the subsets [3] and [1,2] sum to 3. The empty subset sums to 0 ≠ 3, so not counted. Total: 2.
