สมมติว่าเรามีชุดตัวเลข เราต้องสร้างชุดย่อยที่เป็นไปได้ทั้งหมดของชุดนั้น นี้เรียกว่าชุดพลังงาน เราต้องจำไว้ว่าองค์ประกอบอาจซ้ำกัน ดังนั้นหากเซตเป็นเหมือน [1,2,2] เซตกำลังจะเป็น [[], [1], [2], [1,2], [2,2], [1,2,2 ]]
ให้เราดูขั้นตอน -
- กำหนดความละเอียดอาร์เรย์หนึ่งชุดและอีกชุดหนึ่งเรียกว่า x
- เราจะแก้ปัญหานี้โดยใช้วิธีการแบบเรียกซ้ำ ดังนั้นหากชื่อเมธอดแบบเรียกซ้ำเรียกว่า Solve() และนี่ใช้ดัชนี อาร์เรย์ชั่วคราวหนึ่งรายการ และอาร์เรย์ของตัวเลข (nums)
- ฟังก์ชัน Solve() จะทำงานดังนี้ -
- ถ้าดัชนี =ขนาดของ v แล้ว
- หากไม่มี temp ใน x ให้แทรก temp ลงใน res และใส่ temp ลงใน x ด้วย
- คืนสินค้า
- เรียกแก้ปัญหา(ดัชนี + 1, ชั่วคราว, v)
- ใส่ v[index] ลงใน temp
- เรียกแก้ปัญหา(ดัชนี + 1, ชั่วคราว, v)
- ลบองค์ประกอบสุดท้ายออกจากชั่วคราว
- หน้าที่หลักจะเป็นดังนี้ -
- ล้าง res และ x และจัดเรียงอาร์เรย์ที่กำหนด กำหนดอุณหภูมิอาร์เรย์
- เรียกแก้ปัญหา(0, ชั่วคราว, อาร์เรย์)
- จัดเรียงอาร์เรย์ res และส่งคืน res
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector < vector <int> > res;
set < vector <int> > x;
static bool cmp(vector <int> a, vector <int> b){
return a < b;
}
void solve(int idx, vector <int> temp, vector <int> &v){
if(idx == v.size()){
if(x.find(temp) == x.end()){
res.push_back(temp);
x.insert(temp);
}
return;
}
solve(idx+1, temp, v);
temp.push_back(v[idx]);
solve(idx+1, temp, v);
temp.pop_back();
}
vector<vector<int> > subsetsWithDup(vector<int> &a) {
res.clear();
x.clear();
sort(a.begin(), a.end());
vector <int> temp;
solve(0, temp, a);
sort(res.begin(), res.end(), cmp);
return res;
}
};
main(){
Solution ob;
vector<int> v = {1,2,2};
print_vector(ob.subsetsWithDup(v));
} อินพุต
[1,2,2]
ผลลัพธ์
[[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]