作者:
yam276 ('_')
2024-05-20 17:25:33※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言:
: https://leetcode.com/problems/sum-of-all-subset-xor-totals/description
: 1863. Sum of All Subset XOR Totals
: 給你一個陣列nums,求出他的所有子集合裡面的元素相互xor之後的和。
: 思路:
: 1.回溯法,窮舉所有子集合並在途中計算每個子集合的xor結果加總。
在backtrack裡面呼叫兩個backtrack
一個包含自己,一個不包含自己
Code:
impl Solution {
pub fn subset_xor_sum(nums: Vec<i32>) -> i32 {
fn backtrack(nums: &Vec<i32>,
index: usize,
current_xor: i32,
total: &mut i32) {
if index == nums.len() {
*total += current_xor;
return;
}
backtrack(nums, index + 1, current_xor, total);
backtrack(nums, index + 1, current_xor ^ nums[index], total);
}
let mut total = 0;
backtrack(&nums, 0, 0, &mut total);
total
}
}