- 문제
- 문자열로 구성할 수 있는 모든 부분집합을 담아 배열로 리턴
- 사전식 정렬해서 리턴
- 시도
- 우선은 받은 문자열이 중복되지 않게 분리를 하자
- 분리한 문자열을 한개씩 빈 배열에 넣고, 두개부터 문자열의 길이까지 붙여보면서 결과를 담은 배열 내에 중복되지 않으면 푸쉬해서 넣어보자
- 생각보다 2개 이상의 문자열을 만든다는 개념을 짜는게 어려웠다
- 결국은 실패, 빈 스트링이 끼거나 'aba'등 원하지 않던 문자열까지 생성되어 실패
- 수도코드
const powerSet = function (str) {
let chr = [];
for (let i = 0; i < str.length; i++) {
if (!chr.includes(str[i])) {
chr.push(str[i])
chr.sort();
}
}
console.log(chr)
let word = [];
let abc = ''
for (let i = 0; i < chr.length; i++) {
for (let j = 1; j < chr.length; j++) {
if (chr[i] !== chr[j]) {
abc = abc + chr[i]
}
word.push(abc)
abc = ''
}
console.log(word)
}
function makeWord(chr) {
for (let i = 0; i < chr.length; i++) {
if (chr !== chr[i]) {
chr = chr + chr[i]
}
word.push(chr)
}
}
for (let i = 0; i < chr.length; i++) {
makeWord(chr)
}
console.log(word)
let result = [];
for (let i = 0; i < str.length - 1; i++) {
for (let j = 1; j < str.length; j++) {
if (str[i] !== str[j] && !result.includes(str[i] + str[j])) {
result.push(str[i] + str[j])
result.sort();
}
}
}
console.log(result)
};
- 레퍼런스
const powerSet = function (str) {
let chr = [];
for (let i = 0; i < str.length; i++) {
if (!chr.includes(str[i])) {
chr.push(str[i])
chr.sort(); } }
let max = ''
for (let i = 0; i < chr.length; i++) {
max = max + chr[i] }
let result = [];
const filter = function (idx, cur) {
if (idx === max.length) {
result.push(cur)
return }
filter(idx + 1, cur);
filter(idx + 1, cur + max[idx]) }
filter(0, '');
return result.sort()
};