1286.cpp (743B)
1 class Solution { 2 vector<int> vec; 3 const string chars; 4 string res; 5 6 bool has_next = true; 7 void shuffle() { 8 int goal = chars.size() - 1, idx = vec.size() - 1; 9 while (idx > 0 && vec[idx] == goal) 10 goal--, idx--; 11 for (int i = idx, acc = vec[idx]; i < vec.size(); i++) 12 res[i] = chars[vec[i] = ++acc]; 13 if (idx == 0 && vec[0] == goal) has_next = false; 14 } 15 16 public: 17 CombinationIterator(string chars, int len) : chars(chars), vec(len), res(len, ' ') { 18 for (int i = 0; i < len; i++) 19 res[i] = chars[vec[i] = i]; 20 vec.back()--; 21 } 22 23 string next() { 24 shuffle(); 25 return res; 26 } 27 28 bool hasNext() { return has_next; } 29 };