作者yam276 (史萊哲林的優等生)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Mon May 20 17:25:33 2024
※ 引述《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
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.172 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1716197135.A.83F.html
推 JIWP: 別卷了 05/20 17:26
推 SecondRun: 別捲了 05/20 17:26
→ yam276: 好討厭數學解 我就這樣躺平了 05/20 17:27
推 orangeNoob: 別捲了 05/20 17:35