Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- LinkedList
- bst
- stack
- 배열
- Medium
- leetcode
- 카카오
- Linked List
- 공채
- traversal
- Easy
- kakao
- Bit
- tree
- 2019 카카오
- sorting
- 순회
- 리스트
- 완전검색
- Bubble Sort
- 오픈 채팅방
- 트리
- 스택
- Subset
- Math
- 정렬
- binary search tree
- list
Archives
- Today
- Total
미리수얌 블로그
Leetcode: Subsets 본문
Subsets
주어진 배열로 (배열에 있는 숫자들은 모두 unique 함) 만들수 있는 모든 subset을 만들어라.
이 문제는 Bit 로 풀 수 있는데요.
주어진 배열이 31 초과 하지 않으면 가능합니다.
Bit 를 생각해보면
000000 아무것도 넣지 않기
000001 맨 마지막 숫자로만 이루어진 subset
000010 끝에서 두번째 숫자만으로 이루어진 subset
000011 마지막 두개의 숫자로 이루어진 subset
.
.
.
111111 모든 걸 포함하는 subset 으로 만들어지는 것을 알 수 있습니다.
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsets = new LinkedList<>();
int limit = 1 << nums.length;
for (int i = 0; i < limit; ++i) {
int t = i;
int ind = 0;
List<Integer> tmp = new LinkedList<>();
while (t > 0) {
if ((t & 1) == 1) {
tmp.add(nums[ind]);
}
ind++;
t >>>= 1;
}
subsets.add(tmp);
}
return subsets;
}
'코딩문제풀이 > Leetcode' 카테고리의 다른 글
Leetcode: Reverse Words in a String III (0) | 2018.09.29 |
---|---|
LeetCode: Count Numbers with Unique Digits (0) | 2018.09.29 |
LeetCode: Remove Nth Node From End of List (0) | 2018.09.25 |
LeetCode: Letter Combinations of a Phone Number (0) | 2018.09.25 |
LeetCode: Remove Duplicates from Sorted Array (0) | 2018.09.25 |
Comments