Skip to content

Commit

Permalink
Solve: Next Permutation
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Oct 5, 2024
1 parent 18f9aae commit c0969b6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
13 changes: 12 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,18 @@
"*.yarnproject": "jsonc",
"iostream": "cpp",
"vector": "cpp",
"xlocale": "cpp"
"xlocale": "cpp",
"array": "cpp",
"deque": "cpp",
"forward_list": "cpp",
"list": "cpp",
"string": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"string_view": "cpp",
"initializer_list": "cpp",
"regex": "cpp",
"valarray": "cpp"
},
"C_Cpp.errorSquiggles": "disabled"
}
24 changes: 24 additions & 0 deletions LeetCode/Next Permutation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
int i = n - 2;

// Step 1: 오른쪽에서부터 첫 감소하는 위치를 찾기
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}

if (i >= 0) {
// Step 2: 그 값보다 큰 값 중 가장 작은 값과 교체
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(nums[i], nums[j]);
}

// Step 3: i 이후의 배열을 오름차순으로 변경
reverse(nums.begin() + i + 1, nums.end());
}
};

0 comments on commit c0969b6

Please sign in to comment.