[M] 46. Permutations

YJ·3일 전

leetcode

목록 보기
96/100

https://leetcode.com/problems/permutations

문제

주어진 배열에 있는 숫자들로 순열(조합 X) 만들기

답안

public List<List<Integer>> permute(int[] nums) {
	List<List<Integer>> result = new ArrayList<>();
	List<Integer> path = new ArrayList<>();
	boolean[] used = new boolean[nums.length];

	dfs(nums, path, used, result);
	return result;
}

private void dfs(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> result) {
	if (path.size() == nums.length) {
		result.add(new ArrayList<>(path));
		return;
	}
	for (int i = 0; i < nums.length; i++) {
		if (used[i]) {
			continue;
		}
		path.add(nums[i]);
		used[i] = true;

		dfs(nums, path, used, result);

		path.remove(path.size() - 1);
		used[i] = false;
	}
}

메모

순열은.. 이미 선택한 것 안 선택하기만 하면 됨
그래서 boolean[] used 배열로 이미 간 곳 표시해주는 것이 중요함
선택(경로에 추가, 방문 표시) -> dfs -> 백트래킹(경로에서 빼기, 방문 미표시)

profile
Hello

0개의 댓글