diff --git "a/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39. Combination Sum" "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39. Combination Sum" new file mode 100644 index 0000000..b3be849 --- /dev/null +++ "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39. Combination Sum" @@ -0,0 +1,27 @@ +``` python +3回目 +# 時間計算量: O(2^N) +# 空間計算量: O(N) +N = len(candidates) + +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + + all_valid_combination = [] + + def find_vaild_combination(index, current_target, current_combination): + if len(candidates) <= index: + if current_target == 0: + all_valid_combination.append(current_combination[:]) + return + + if candidates[index] <= current_target: + current_combination.append(candidates[index]) + find_vaild_combination(index, current_target-candidates[index], current_combination) + current_combination.pop() + + find_vaild_combination(index+1, current_target, current_combination) + + find_vaild_combination(0, target, []) + return all_valid_combination +``` diff --git "a/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39.-Combination-Sum 4th.md" "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39.-Combination-Sum 4th.md" new file mode 100644 index 0000000..c98a303 --- /dev/null +++ "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/39.-Combination-Sum 4th.md" @@ -0,0 +1,24 @@ +### 時間: 3m51s +### Error: 0 +### 時間計算量: O(len(candidates)^(target/min(candidates) + 1)) +### 空間計算量: O(target/min(candidates) + space for Answer) +``` +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + result = [] + combination = [] + + def find_all_combiantions(index, current_target, combination): + if index == len(candidates): + if current_target == 0: + result.append(combination) + return + + if candidates[index] <= current_target: + find_all_combiantions(index, current_target - candidates[index], combination + [candidates[index]]) + + find_all_combiantions(index + 1, current_target, combination) + + find_all_combiantions(0, target, []) + return result +```