#include <iostream> #include <vector> using namespace std; class Solution { private: vector<vector<int>> result; // 结果集 int five_count = 0; // 队列中拿着0.5元的人数计数器 int one_count = 0; // 队列中拿着1元的人数计数器 public: vector<vector<int>> queueShop(int n) { vector<int> each_case; each_case.clear(); result.clear(); backtracking(each_case, n); return result; } void backtracking(vector<int> &each_case, int n) { if (each_case.size() == 2 * n) { result.emplace_back(each_case); return; } if (five_count < n) { each_case.emplace_back(5); five_count++; backtracking(each_case, n); each_case.pop_back(); five_count--; } /* 只有当前队列中0.5元的数目多于1元时才考虑继续加入1元 */ if (one_count < n && five_count > one_count) { each_case.emplace_back(1); one_count++; backtracking(each_case, n); each_case.pop_back(); one_count--; } } }; int main(int argc, char *argv[]) { Solution solution; auto res = solution.queueShop(5); for (const auto &i : res) { for (const auto &j : i) { cout << j << " "; } cout << endl; } }帮我改成python语言
时间: 2024-01-29 21:02:28 浏览: 98
以下是将该C++代码转换成Python的代码:
```python
class Solution:
def __init__(self):
self.result = [] # 结果集
self.five_count = 0 # 队列中拿着0.5元的人数计数器
self.one_count = 0 # 队列中拿着1元的人数计数器
def queueShop(self, n: int) -> List[List[int]]:
each_case = []
self.result.clear()
self.backtracking(each_case, n)
return self.result
def backtracking(self, each_case: List[int], n: int) -> None:
if len(each_case) == 2 * n:
self.result.append(each_case[:])
return
if self.five_count < n:
each_case.append(5)
self.five_count += 1
self.backtracking(each_case, n)
each_case.pop()
self.five_count -= 1
# 只有当前队列中0.5元的数目多于1元时才考虑继续加入1元
if self.one_count < n and self.five_count > self.one_count:
each_case.append(1)
self.one_count += 1
self.backtracking(each_case, n)
each_case.pop()
self.one_count -= 1
if __name__ == '__main__':
solution = Solution()
res = solution.queueShop(5)
for i in res:
print(i)
```
阅读全文